package com.yanqu.road.server.manager.peakstronghold;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.peakstronghold.*;
import com.yanqu.road.entity.activity.peakstronghold.config.*;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.log.cross.LogCrossPeakHoldGuess;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.logic.bussiness.activity.PeakStrongholdActivityBusiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.pb.activity.StrongholdWarProto;
import com.yanqu.road.pb.activity.TwinsProto;
import com.yanqu.road.pb.commonactivity.CommonActivityProto;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.pb.rank.UnionActivityRankProto;
import com.yanqu.road.server.connect.CrossAgentLinkedControl;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.activity.peakseacraft.PeakSeacraftMgr;
import com.yanqu.road.server.manager.log.CrossActivityLogMgr;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.manager.strongholdwar.AttackResult;
import com.yanqu.road.server.manager.strongholdwar.AttackUnionResult;
import com.yanqu.road.server.manager.strongholdwar.CrossStrongholdActivityMgr;
import com.yanqu.road.server.manager.strongholdwar.MammonHelpResult;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manager.yrank.CrossYRankMgr;
import com.yanqu.road.server.pb.CrossPeakStrongholdPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PeakStrongholdActivityModel {
    private int unionGroup;//商会分组

    private int activityId;

    private PeakStrongHoldConfig config = null;

    //竞猜数据
    private Map<Long, CrossPeakStrongholdUserGuessData> userGuessDataMap = new ConcurrentHashMap<>();
    //轮次 每一个玩 家的竞猜数据 淘汰赛
    private Map<Integer, Map<Long, List<String>>> userSelectGuessMap = new ConcurrentHashMap<>();
    //每一个玩家的竞猜数据 决赛
    private Map<Long, List<String>> userFinalsGuessMap = new ConcurrentHashMap<>();
    //轮次 每个商会竞猜人数
    private Map<Integer,Map<String,Integer>> userSelectGuessCountMap = new ConcurrentHashMap<>();
    private Map<String,Integer> userFinalsGuessCountMap = new ConcurrentHashMap<>();

    //猜对对应次数的人数
    private Map<Integer,Map<Integer,Integer>> rightGuessCountMap = new ConcurrentHashMap<>();
    //猜对对应次数的人
    private Map<Integer,Map<Integer,List<Long>>> rightGuessUserMap = new ConcurrentHashMap<>();


    private List<CrossConditionSyncData> conditionSyncDataList = new ArrayList<>();
    //去商会跨服拉取对应商会需要职位
    private List<String> unionScoreSyncList = new ArrayList<>();

    //轮次 商会id 据点数据
    private Map<Integer, Map<String, CrossPeakStrongholdDefendUnionData>> defendUnionsMap;
    private Map<Integer, Map<Integer, List<CrossPeakStrongholdDefendUnionData>>> defendUnionsGroupMap;//按分组索引
    private Map<String, CrossPeakStrongholdUnionData> unionDataMap;
    private Map<String, Long> lastUnionUpdateTimeMap = new ConcurrentHashMap<>();
    private Map<String, Long> lastUnionDeleteTimeMap = new ConcurrentHashMap<>();

    //商会的历史最高门客赚钱缓存
//    private Map<String, CrossUnionAbilityCacheData> unionMemberAbilityMap = new ConcurrentHashMap<>();
    private CrossPeakStrongholdCacheData cacheData;
    private long waitEndTime = 0;//最大等待结束时间,超过时间报警后台等待处理
    private List<CrossPeakStrongholdUnionData> waitCreateDefendUnions = new ArrayList<>();//等待生成据点的商会

    private static int waitMaxTime = 600;
    //积分排行和捐献排行不会有新增商会,直接这里管理
    private List<CrossPeakStrongholdUnionData> unionScoreRankList = new ArrayList<>();
    private List<CrossPeakStrongholdUnionData> unionSilverRankList = new ArrayList<>();
    private List<PeakStrongholdUnionMemberInfo> memberDamageRankList = new ArrayList<>();//玩家伤害排行
    private Map<Integer, List<CrossPeakStrongholdDefendUnionData>> unionRoundDamageRank = new ConcurrentHashMap<>();//组内伤害排行
    private Map<Integer,Map<Integer, PeakStrongholdUnionMemberInfo>> groupFirstMemberMap = new ConcurrentHashMap<>(); //组内伤害第一的玩家
    private List<CrossPeakStrongholdUnionData> unionNowRankScoreRankList = new ArrayList<>(); //战斗期间实时的积分排名


    //商会报名期排行管理
    private List<CrossUnionAbilityRankData> abilityRankList = new ArrayList<>();
    private Map<String, CrossUnionAbilityRankData> abilityRankMap = new ConcurrentHashMap<>();
    private static RandomHelper randomHelper = new RandomHelper();
    private Map<String, Lock> unionLock = new ConcurrentHashMap<>();
    private Map<Integer, Lock> groupLock = new ConcurrentHashMap<>();

    private Map<Integer, List<Long>> waitNotifyRespServerIds = new ConcurrentHashMap<>();
    private int waitAmount = 0;
    private boolean abilityRankChangeMark = false;
    private boolean damageRankChangeMark = false;

    //6.5 新增使用道具间隔时间
    private Map<Long,Long> mammonHelpLastTimeMap;

    private UnionActivityRankProto.UnionActivityRankListMsg.Builder nowScoreRankListMsg = UnionActivityRankProto.UnionActivityRankListMsg.newBuilder();


    public PeakStrongholdActivityModel(int activityId, PeakStrongHoldConfig peakConfig, int unionGroup) {
        this.activityId = activityId;
        this.config = peakConfig;
        this.unionGroup = unionGroup;
        this.mammonHelpLastTimeMap = new ConcurrentHashMap<>();
        reload();
    }

    public void save() {
        if (null != cacheData) {
            synchronized (cacheData) {
                if (cacheData.isInsertOption()) {
                    PeakStrongholdActivityBusiness.addCrossPeakStrongholdCacheData(cacheData);
                } else if (cacheData.isUpdateOption()) {
                    PeakStrongholdActivityBusiness.updateCrossPeakStrongholdCacheData(cacheData);
                }
            }
        }

        if (null != defendUnionsMap) {
            List<CrossPeakStrongholdDefendUnionData> dataList = new ArrayList<>();
            synchronized (defendUnionsMap) {
                for (Map<String, CrossPeakStrongholdDefendUnionData> dataMap : defendUnionsMap.values()) {
                    for (CrossPeakStrongholdDefendUnionData data : dataMap.values()) {
                        dataList.add(data);
                    }
                }
            }
            for (CrossPeakStrongholdDefendUnionData data : dataList) {
                if (data.isInsertOption()) {
                    PeakStrongholdActivityBusiness.addCrossPeakStrongholdDefendUnionData(data);
                } else if (data.isUpdateOption()) {
                    PeakStrongholdActivityBusiness.updateCrossPeakStrongholdDefendUnionData(data);
                }
            }
        }

        if (null != unionDataMap) {
            List<CrossPeakStrongholdUnionData> dataList = new ArrayList<>();
            synchronized (unionDataMap) {
                dataList.addAll(unionDataMap.values());
            }

            for (CrossPeakStrongholdUnionData data : dataList) {
                if (data.isInsertOption()) {
                    PeakStrongholdActivityBusiness.addCrossPeakStrongholdUnionData(data);
                } else if (data.isUpdateOption()) {
                    PeakStrongholdActivityBusiness.updateCrossPeakStrongholdUnionData(data);
                }
            }
        }

//        if (null != unionMemberAbilityMap) {
//            List<CrossUnionAbilityCacheData> dataList = new ArrayList<>();
//            synchronized (unionMemberAbilityMap) {
//                dataList.addAll(unionMemberAbilityMap.values());
//            }
//            for (CrossUnionAbilityCacheData data : dataList) {
//                if (data.isInsertOption()) {
//                    PeakStrongholdActivityBusiness.addCrossUnionAbillityCacheData(data);
//                } else if (data.isUpdateOption()) {
//                    PeakStrongholdActivityBusiness.updateCrossUnionAbillityCacheData(data);
//                }
//            }
//        }

//        List<CrossUnionAbilityRankData> rankList = getAbilityRankList();
//        for (CrossUnionAbilityRankData rankData : rankList) {
//            if (rankData.isInsertOption()) {
//                PeakStrongholdActivityBusiness.addCrossUnionAbilityRankData(rankData);
//            } else if (rankData.isUpdateOption()) {
//                PeakStrongholdActivityBusiness.updateCrossUnionAbilityRankData(rankData);
//            }
//        }

        if (null != userGuessDataMap) {
            List<CrossPeakStrongholdUserGuessData> dataList = new ArrayList<>();
            synchronized (userGuessDataMap) {
                dataList.addAll(userGuessDataMap.values());
            }

            for (CrossPeakStrongholdUserGuessData guessData : dataList) {
                if (guessData.isInsertOption()) {
                    PeakStrongholdActivityBusiness.addCrossUserGuessData(guessData);
                } else if (guessData.isUpdateOption()) {
                    PeakStrongholdActivityBusiness.updateCrossUserGuessData(guessData);
                }
            }
        }

    }

    private void reload() {
        ePeakStrongholdStageType stageType = config.getStageType();

        abilityRankList.clear();
        abilityRankMap.clear();


        cacheData = PeakStrongholdActivityBusiness.getCrossPeakStrongholdCacheData(activityId, unionGroup);
        if (null == cacheData) {
            cacheData = new CrossPeakStrongholdCacheData(activityId, unionGroup);
            cacheData.setStageType(ePeakStrongholdStageType.BeginInShow.getValue());
            cacheData.setRound(0);
            cacheData.setWaitServerIds(new ArrayList<>());
            cacheData.setInsertOption();
        }
//        if (stageType.getValue() == ePeakStrongholdStageType.Registration.getValue()) {
//            //时间在报名期，把状态设置为开始展示，走状态机检测
//            cacheData.setStageType(ePeakStrongholdStageType.BeginInShow.getValue());
//        }
        if (this.cacheData.getStageType() == ePeakStrongholdStageType.WaitUpdateEnd.getValue()) {
            this.waitEndTime = DateHelper.getCurrentSecond() + waitMaxTime;
        } else if (this.cacheData.getStageType() == ePeakStrongholdStageType.HoldDefendCreate.getValue()) {
            for (Long serverId : this.cacheData.getWaitServerIds()) {
                addWaitNotifyServerIds(Protocol.S_PEAK_STRONGHOLD_ELIMINATE_UNION_LIST, serverId);
            }
            this.waitEndTime = DateHelper.getCurrentSecond() + waitMaxTime;
        }

        //淘汰赛没开始要加载
//        abilityRankList = PeakStrongholdActivityBusiness.getCrossUnionAbilityRankData(activityId);
//        for (CrossUnionAbilityRankData rankData : abilityRankList) {
//            abilityRankMap.put(rankData.getUnionId(), rankData);
//        }

        unionScoreRankList.clear();
        unionSilverRankList.clear();
        memberDamageRankList.clear();

        defendUnionsMap = PeakStrongholdActivityBusiness.getCrossPeakStrongholdDefendUnionData(activityId, unionGroup);
        unionDataMap = PeakStrongholdActivityBusiness.getCrossPeakStrongholdUnionData(activityId, unionGroup);
        for (CrossPeakStrongholdUnionData unionData : unionDataMap.values()) {
            if (!unionData.isCreateDefend()) {
                waitCreateDefendUnions.add(unionData);
            }

            //排行容器
            unionScoreRankList.add(unionData);

            if (unionData.getTotalDonateSilver().compareTo(BigInteger.ZERO) == 1) {//有捐献的才放进去
                unionSilverRankList.add(unionData);
            }
            synchronized (memberDamageRankList){
                for (PeakStrongholdUnionMemberInfo memberInfo : unionData.getMemberInfoMap().values()) {
                    memberDamageRankList.add(memberInfo);
                    updateGroupFirstDamageMember(this.cacheData.getRound(),unionData.getGroup(), memberInfo);
                }
            }
        }

        //建立防守据点的组索引
        defendUnionsGroupMap = new ConcurrentHashMap<>();
        for (Map<String, CrossPeakStrongholdDefendUnionData> dataMap : defendUnionsMap.values()) {
            for (CrossPeakStrongholdDefendUnionData data : dataMap.values()) {
                Map<Integer, List<CrossPeakStrongholdDefendUnionData>> groupDataMap = defendUnionsGroupMap.get(data.getRound());
                if (null == groupDataMap) {
                    groupDataMap = new ConcurrentHashMap<>();
                    defendUnionsGroupMap.put(data.getRound(), groupDataMap);
                }
                List<CrossPeakStrongholdDefendUnionData> dataList = groupDataMap.get(data.getGroup());
                if (null == dataList) {
                    dataList = new ArrayList<>();
                    groupDataMap.put(data.getGroup(), dataList);
                }
                dataList.add(data);

                if (data.getRound() == this.cacheData.getRound()) {//组内排名管理
                    List<CrossPeakStrongholdDefendUnionData> groupList = unionRoundDamageRank.get(data.getGroup());
                    if (null == groupList) {
                        groupList = new ArrayList<>();
                        unionRoundDamageRank.put(data.getGroup(), groupList);
                    }
                    groupList.add(data);
                }
            }
        }

        initGuessData();

        unionScoreRankChangeSort();
        unionSilverRankChange();
        unionAbilityRankChange();
        memberDamageRankChange();
        initRoundDamageRank();

        createDefendUnionByTimerTask();
    }

    private void initGuessData(){
        userGuessDataMap = PeakStrongholdActivityBusiness.getCrossUserGuessData(activityId, unionGroup);
        for(CrossPeakStrongholdUserGuessData guessData : userGuessDataMap.values()){
            if(guessData.getGuessFinalsMap().size() > 0){
                userFinalsGuessMap.put(guessData.getUserId(),guessData.getGuessFinalsMap());
            }
            if(guessData.getGuessWinMap().size() > 0){
                for(int timeId : guessData.getGuessWinMap().keySet()){
                    if(!userSelectGuessMap.containsKey(timeId)){
                        userSelectGuessMap.put(timeId,new ConcurrentHashMap<>());
                    }
                    userSelectGuessMap.get(timeId).put(guessData.getUserId(),guessData.getGuessWinMap().get(timeId));
                }
            }
        }
        for(PeakStrongholdTimeConfig timeConfig : config.getTimeConfigMap().values()){
            initGamebleRight(timeConfig.getTimeId());
        }
        initGamebleRight(0);
    }

    public Map<Integer, Map<String, CrossPeakStrongholdDefendUnionData>> getDefendUnionsMap() {
        return defendUnionsMap;
    }

    public void setDefendUnionsMap(Map<Integer, Map<String, CrossPeakStrongholdDefendUnionData>> defendUnionsMap) {
        this.defendUnionsMap = defendUnionsMap;
    }

    public CrossPeakStrongholdDefendUnionData getDefendUnionData(int round, String unionId) {
        synchronized (defendUnionsMap) {
            if (this.defendUnionsMap.containsKey(round)) {
                return this.defendUnionsMap.get(round).get(unionId);
            }
        }
        return null;
    }

    public List<CrossPeakStrongholdDefendUnionData> getDefendUnionDataList(int round, int group) {
        Map<Integer, List<CrossPeakStrongholdDefendUnionData>> groupDataMap = defendUnionsGroupMap.get(round);
        if (null != groupDataMap) {
            return groupDataMap.get(group);
        }
        return null;
    }

    public void addDefendUnionData(int round, CrossPeakStrongholdDefendUnionData unionData) {
        synchronized (defendUnionsMap) {
            Map<String, CrossPeakStrongholdDefendUnionData> dataMap = this.defendUnionsMap.get(round);
            if (null == dataMap) {
                dataMap = new HashMap<>();
                this.defendUnionsMap.put(round, dataMap);
            }
            dataMap.put(unionData.getUnionId(), unionData);

            Map<Integer, List<CrossPeakStrongholdDefendUnionData>> groupDataMap = defendUnionsGroupMap.get(round);
            if (null == groupDataMap) {
                groupDataMap = new ConcurrentHashMap<>();
                defendUnionsGroupMap.put(round, groupDataMap);
            }
            List<CrossPeakStrongholdDefendUnionData> dataList = groupDataMap.get(unionData.getGroup());
            if (null == dataList) {
                dataList = new ArrayList<>();
                groupDataMap.put(unionData.getGroup(), dataList);
            }
            dataList.add(unionData);
        }
    }

    public Map<String, CrossPeakStrongholdUnionData> getUnionDataMap() {
        return unionDataMap;
    }

    public void setUnionDataMap(Map<String, CrossPeakStrongholdUnionData> unionDataMap) {
        this.unionDataMap = unionDataMap;
    }

    public long getLastUnionUpdateTime(String unionId) {
        if (lastUnionUpdateTimeMap.containsKey(unionId)) {
            return lastUnionUpdateTimeMap.get(unionId);
        }
        return 0;
    }

    public void setLastUnionUpdateTime(String unionId, long lastUnionUpdateTime) {
        lastUnionUpdateTimeMap.put(unionId, lastUnionUpdateTime);
    }

    public long getLastUnionDeleteTime(String unionId) {
        if (lastUnionDeleteTimeMap.containsKey(unionId)) {
            return lastUnionDeleteTimeMap.get(unionId);
        }
        return 0;
    }

    public void setLastUnionDeleteTime(String unionId, long lastTime) {
        lastUnionDeleteTimeMap.put(unionId, lastTime);
    }

    //这个方法会创建据点数据,只在淘汰赛调用
    private CrossPeakStrongholdUnionData getAndCreateUnionData(int activityId, String unionId) {
        CrossPeakStrongholdUnionData unionData = this.unionDataMap.get(unionId);
        if (null == unionData) {
            synchronized (unionDataMap) {
                unionData = this.unionDataMap.get(unionId);
                if (null == unionData) {
                    unionData = new CrossPeakStrongholdUnionData(activityId, unionGroup, unionId);
                    unionData.setMemberInfoMap(new HashMap<>());
                    unionData.setDefendPatrons(new HashMap<>());
                    unionData.setRandSeed(CrossPeakStrongholdActivityMgr.getSortRandSeed());
                    this.unionDataMap.put(unionId, unionData);
                    this.unionScoreRankList.add(unionData);
                    this.unionNowRankScoreRankList.add(unionData);
                }
            }
        }
        return unionData;
    }

    public CrossPeakStrongholdUnionData getUnionData(String unionId) {
        return this.unionDataMap.get(unionId);
    }

    //据点战阶段状态检查
    public void checkStageTypeChange() {
        ePeakStrongholdStageType newStageType = config.getStageType();
        if (this.cacheData.getStageType() == newStageType.getValue() && this.cacheData.getRound() >= config.getRound()) {
            if (this.cacheData.getRound() > config.getRound()) {
                this.cacheData.setWaitError(ePeakStrongholdErrorType.RoundMore.getValue());
            }
            return;
        }

        synchronized (cacheData) {
            //时间对应的状态和跑的状态不一致会进来检测
            switch (ePeakStrongholdStageType.forValue(this.cacheData.getStageType())) {
                case BeginInShow: {//刚启动时如果在报名会设置为开始展示,这里会修正为正确的阶段
                    //展示进入报名,通知游戏服上传总赚钱,走通用巅峰报名期数据,这里不请求了
//                    for (long serverId : config.getActivityInfo().getServerIdList()) {
//                        MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_PEAK_STRONGHOLD_NOTIFY_UPDATE_ABILITY_INFO, ""));
//                        addWaitNotifyServerIds(Protocol.S_PEAK_STRONGHOLD_NOTIFY_UPDATE_ABILITY_INFO, serverId);
//                    }
                    this.cacheData.setStageType(ePeakStrongholdStageType.Registration.getValue());
                    CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 进入报名阶段！！");
                }
                break;
                case Registration: {
                    if (isWaitServerCode(Protocol.S_PEAK_UNION_MAX_ABILITY_RANK_LOCK)) {
                        CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 等待锁定名单返回");
                        return;
                    }
                    //报名进入准备阶段,进入据点生成阶段,获取淘汰赛商会,并下发名单和通知上传防守门客
                    this.cacheData.setStageType(ePeakStrongholdStageType.WaitUpdateEnd.getValue());

                    this.waitEndTime = DateHelper.getCurrentSecond() + 10;//最多等待10s
                    UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, unionGroup);
                    for (long serverId : groupData.getServerSet()) {
                        if (!CrossAgentLinkedControl.isSeverIdConnection(serverId)) {
                            continue;
                        }
                        MessageHelper.sendPacket(serverId, 0,
                                YanQuMessageUtils.buildMessage(GameProtocol.S_PEAK_UNION_MAX_ABILITY_RANK_LOCK,
                                        CommonActivityProto.CommonActivityRankListReqMsg.newBuilder().setGroupId(unionGroup).setActivityId(config.getActivityInfo().getActivityId())));
                        break;
                    }
//                    cacheData.getWaitServerIds().clear();
//                    for (long serverId : config.getActivityInfo().getServerIdList()) {
//                        cacheData.getWaitServerIds().add(serverId);
//                        cacheData.setUpdateOption();
//                        MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_PEAK_STRONGHOLD_NOTIFY_WAIT_UPDATE_END_CONFIRM, ""));
//                        addWaitNotifyServerIds(Protocol.S_PEAK_STRONGHOLD_NOTIFY_WAIT_UPDATE_END_CONFIRM, serverId);
//                    }
                    CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 报名阶段结束, 等待数据同步结束！！");
                }
                break;
                case WaitUpdateEnd: {
                    if (DateHelper.getCurrentSecond() >= this.waitEndTime) {
                        //超过等待时间
                        this.waitEndTime = DateHelper.getCurrentSecond() + 10;//再等10秒
                        this.cacheData.setWaitError(ePeakStrongholdErrorType.WaitAbility.getValue());
                        CrossPeakStrongholdMgr.getLogger().error("巅峰据点战 报名结束等{}秒后，还没收到报名期名单", 10);
                        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, unionGroup);
                        for (long serverId : groupData.getServerSet()) {
                            if (!CrossAgentLinkedControl.isSeverIdConnection(serverId)) {
                                continue;
                            }
                            MessageHelper.sendPacket(serverId, 0,
                                    YanQuMessageUtils.buildMessage(GameProtocol.S_PEAK_UNION_MAX_ABILITY_RANK_LOCK,
                                            CommonActivityProto.CommonActivityRankListReqMsg.newBuilder().setGroupId(unionGroup).setActivityId(config.getActivityInfo().getActivityId())));
                            break;
                        }
                    } else {
                        CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 报名结束等待数据同步中....");
                    }
                }
                break;
                case HoldCreate: {//据点生成阶段,等待据点生成,据点生成后进入准备阶段
                    CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 等待据点数据生成中....");
                    if (this.waitCreateDefendUnions.isEmpty()) {//据点生成完进入准备阶段
                        calcUnionDefendData();//计算一次血量
                        this.cacheData.setStageType(ePeakStrongholdStageType.Prepare.getValue());

                        //释放之前回合的数据
                        clearOldRoundData();

                        CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 据点数据生成结束,进入准备阶段！");
                    }
                }
                break;
                case Prepare: {//准备阶段进入比赛阶段,进入防守数据生成阶段,等待据点防守数据固定,
                    this.cacheData.setStageType(ePeakStrongholdStageType.HoldDefendCreate.getValue());
                    //准备到开始比赛,通知游戏服确认准备阶段的数据传完没有
                    this.waitEndTime = DateHelper.getCurrentSecond() + waitMaxTime;//最多等待10分钟
                    UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, unionGroup);
                    for (long serverId : groupData.getServerSet()) {
                        this.cacheData.getWaitServerIds().add(serverId);
                        this.cacheData.setUpdateOption();
                        MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_PEAK_STRONGHOLD_NOTIFY_WAIT_PREPARE_UPDATE_END_CONFIRM,
                                PeakStrongholdWarProto.CrossPeakHoldCommonMsg.newBuilder().setActivityId(activityId).setUnionGroup(unionGroup)));
                        addWaitNotifyServerIds(Protocol.S_PEAK_STRONGHOLD_NOTIFY_WAIT_PREPARE_UPDATE_END_CONFIRM, serverId);
                    }
                    CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 准备阶段结束,进入据点防守数据生成阶段！");
                }
                break;
                case HoldDefendCreate: {//确认防守数据全部生成后,进入正式比赛阶段
                    if (this.cacheData.getWaitServerIds().isEmpty()) {
                        //更新排名
                        timerRankSort();
                        calcUnionDefendData();
                        this.cacheData.setStageType(ePeakStrongholdStageType.InBattle.getValue());
                        this.cacheData.setWaitError(0);
                        CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 进入淘汰赛战斗阶段！");
                    } else if (DateHelper.getCurrentSecond() >= this.waitEndTime) {
                        //超过等待时间
                        this.waitEndTime += 10;//再等10分钟
                        this.cacheData.setWaitError(ePeakStrongholdErrorType.WaitDefend.getValue());
                        CrossPeakStrongholdMgr.getLogger().error("巅峰据点战进入淘汰赛 等{}秒后，还有游戏服{}没传完数据", waitMaxTime, cacheData.getWaitServerIds());
                        for (long serverId : cacheData.getWaitServerIds()) {

                            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_PEAK_STRONGHOLD_NOTIFY_WAIT_PREPARE_UPDATE_END_CONFIRM,
                                    PeakStrongholdWarProto.CrossPeakHoldCommonMsg.newBuilder().setActivityId(activityId).setUnionGroup(unionGroup)));
                            addWaitNotifyServerIds(Protocol.S_PEAK_STRONGHOLD_NOTIFY_WAIT_PREPARE_UPDATE_END_CONFIRM, serverId);
                        }
                    } else {
                        CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 准备阶段结束,还有服务器数[{}]没传完,等待防守数据传完....", this.cacheData.getWaitServerIds().size());
                    }
                }
                break;
                case InBattle: {//比赛阶段只会进入准备和结束,所以直接更新阶段
                    if (Config.isDebug()) {
                        CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 淘汰赛战斗阶段结束！round={}", this.cacheData.getRound());
                    }
                    PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(this.cacheData.getStageType(), this.cacheData.getRound());
                    if (null == timeConfig) {
                        CrossPeakStrongholdMgr.getLogger().error("巅峰据点战 淘汰赛战斗阶段结束,timeConfig取不到配置！round={}", this.cacheData.getRound());
                        return;//报错取不到配置！异常！
                    }
                    //一轮淘汰赛结束，比赛阶段进入准备阶段,更新淘汰赛名单
                    //淘汰赛结束重置捐献排行
                    for (CrossPeakStrongholdUnionData unionData : unionScoreRankList) {
                        unionData.roundReset(this.cacheData.getRound());
                    }
//                unionSilverRankList.clear();

                    //积分结算
                    socreRankSettle();

                    if (this.cacheData.getRound() == config.getTotalRound()) {
                        this.cacheData.setStageType(ePeakStrongholdStageType.EndInShow.getValue());
                        if (this.cacheData.getStageType() != config.getStageType().getValue()) {
                            CrossPeakStrongholdActivityMgr.getLogger().error("巅峰据点战实际跑的状态和时间对应的配置状态对不上！！");
                        }
                        //冠亚军竞猜
                        guessChampionResult();

                    } else {//最后一回合结束不分组
                        this.cacheData.setStageType(ePeakStrongholdStageType.HoldCreate.getValue());
                        if (this.cacheData.getRound() < config.getRound()) {
                            this.cacheData.setRound(this.cacheData.getRound() + 1);
                        }
                        //积分排行分组
                        devideIntoGroupsByScoreRank(timeConfig);

                        guessWinResult(timeConfig.getTimeId());
                    }
                }
                break;
                default:
                    break;
            }
        }
    }

    private void addWaitNotifyServerIds(int code, long serverId){
        List<Long> waitServerIds = waitNotifyRespServerIds.get(code);
        if (waitServerIds == null) {
            synchronized (waitNotifyRespServerIds) {
                waitServerIds = waitNotifyRespServerIds.get(code);
                if (waitServerIds == null) {
                    waitServerIds = new ArrayList<>();
                    waitNotifyRespServerIds.put(code, waitServerIds);
                }
                if (!waitServerIds.contains(serverId)) {
                    waitServerIds.add(serverId);
                }
            }
        }
        synchronized (waitNotifyRespServerIds) {
            if(!waitServerIds.contains(serverId)){
                waitServerIds.add(serverId);
            }
        }
    }

    private boolean isWaitServerCode(int code) {
        List<Long> waitServerIds = waitNotifyRespServerIds.get(code);
        if (null == waitServerIds || waitServerIds.isEmpty()) {
            return false;
        }
        return true;
    }

    public void checkNotifyServerIds() {
        if (waitNotifyRespServerIds.isEmpty()) {
            return;
        }
        this.waitAmount++;
        if (waitAmount >= 6) {//每隔6s检查一下通知的服务器有没有返回
            waitAmount = 0;
            synchronized (waitNotifyRespServerIds) {
                for (Map.Entry<Integer, List<Long>> waitServerIdsMap : waitNotifyRespServerIds.entrySet()) {
                    int code = waitServerIdsMap.getKey();
                    List<Long> waitServerIds = waitServerIdsMap.getValue();
                    if (null == waitServerIds || waitServerIds.isEmpty()) {
                        continue;
                    }
                    waitServerIds.forEach(serverId -> {
                        if (code == Protocol.S_PEAK_STRONGHOLD_ELIMINATE_UNION_LIST) {
                            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(code, CrossPeakStrongholdPb.buildEliminateUnionListMsg(unionScoreRankList, this.cacheData.getRound(), unionGroup)));
                        } else {
                            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(code, PeakStrongholdWarProto.CrossPeakHoldCommonMsg.newBuilder().setActivityId(activityId).setUnionGroup(unionGroup)));
                        }
                    });
                }
            }
        }
    }

    public void confirmReceiveCode(long serverId, int code) {
        if (waitNotifyRespServerIds.isEmpty()) {
            return;
        }
        this.waitAmount = 0;
        List<Long> waitServerIds = waitNotifyRespServerIds.get(code);
        if (null != waitServerIds && !waitServerIds.isEmpty()) {
            synchronized (waitNotifyRespServerIds) {
                waitServerIds = waitNotifyRespServerIds.get(code);
                if (null != waitServerIds && !waitServerIds.isEmpty()) {
                    waitServerIds.remove(serverId);
                    if (waitServerIds.isEmpty()) {
                        waitNotifyRespServerIds.remove(code);
                    }
                }
            }
        }

        if (Config.isDebug()) {
            CrossPeakStrongholdActivityMgr.getLogger().info("巅峰据点战 游戏服{}确认收到协议{}", serverId, code);
        }
    }

    //游戏服返回的上传结束确认
    public void updateDataEndConfirm(long serverId, int remainAmount, long openTime) {
        synchronized (cacheData) {
            if (remainAmount == 0) {
                if (cacheData.getWaitServerIds().contains(serverId)) {
                    cacheData.getWaitServerIds().remove(serverId);
                }
            }

            long minOpenTime = cacheData.getMinOpenTime();
            if (minOpenTime == 0) {
                minOpenTime = openTime;
            } else if (minOpenTime > openTime) {
                minOpenTime = openTime;
            }
            cacheData.setMinOpenTime(minOpenTime);

            cacheData.setUpdateOption();
        }


        CrossPeakStrongholdActivityMgr.getLogger().info("巅峰据点战  游戏服{}返回确认,剩余未传玩家数={}", serverId, remainAmount);
    }

    public List<CrossPeakStrongholdUnionData> takeWaitCreateDefendUnion() {
        List<CrossPeakStrongholdUnionData> takeUnion = new ArrayList<>();

        synchronized (this.waitCreateDefendUnions) {
            for (CrossPeakStrongholdUnionData unionData : this.waitCreateDefendUnions) {
                takeUnion.add(unionData);
            }
        }
        return takeUnion;
    }

    public void removeWaitCreateDefendUnion(CrossPeakStrongholdUnionData data) {
        synchronized (this.waitCreateDefendUnions) {
            this.waitCreateDefendUnions.remove(data);
        }
    }

    //商会分组,unionDatas,分组规则，根据总商会数量和每组需求数量，确定组数
    public void devideIntoGroups(List<CrossPeakStrongholdUnionData> unionDatas, List<CrossPeakStrongholdUnionData> notRiseUpUnions) {
        for(int groupId : unionRoundDamageRank.keySet()){
            updateRoundDamageRank(groupId);
        }

        int groupPerNum = config.getGroupPerNum();
        int i = unionDatas.size() % groupPerNum;
        int groupNeed = unionDatas.size() / groupPerNum;
        if (i != 0) {
            groupNeed++;
        }


        PeakStrongholdWarProto.CrossPeakHoldEliminateUnionListMsg.Builder unionListMsg = PeakStrongholdWarProto.CrossPeakHoldEliminateUnionListMsg.newBuilder();
        unionListMsg.setRound(this.cacheData.getRound());
        unionListMsg.setIsBroadcast(true);
        unionListMsg.setUnionGroup(this.unionGroup);

        int group = 1;
        Set<Integer> updateGroups = new HashSet<>();
        for (int r = 0; r < unionDatas.size(); r++) {
            CrossPeakStrongholdUnionData unionData = unionDatas.get(r);
            if (unionData == null) {
                continue;
            }
            if (!updateGroups.contains(group)) {
                updateGroups.add(group);
                updateRoundDamageRank(group);
            }
            unionData.setGroup(group);
            if (Config.isDebug()) {
                CrossPeakStrongholdActivityMgr.getLogger().info("round={},分组----排名{}=分组{}-----", this.cacheData.getRound(), r + 1, group);
            }

            PeakStrongholdWarProto.PeakHoldUnionRoundEndMsg.Builder riseUpMsg = PeakStrongholdWarProto.PeakHoldUnionRoundEndMsg.newBuilder();
            riseUpMsg.setUnionId(unionData.getUnionId());
            riseUpMsg.setIsRiseUp(true);
            riseUpMsg.setGroupRank(0);
            riseUpMsg.setGroup(0);
            CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(this.cacheData.getRound() - 1, unionData.getUnionId());
            if (null != defendUnionData) {
                riseUpMsg.setGroupRank(defendUnionData.getGroupRank());
                riseUpMsg.setGroup(defendUnionData.getGroup());
            }
            riseUpMsg.setTotalRank(unionData.getRank());
            unionListMsg.addRiseUpUnions(riseUpMsg);
            group++;
            if (group > groupNeed) {
                group = 1;
            }
        }

        updateNowScoreRank();

        if (null != notRiseUpUnions) {
            notRiseUpUnions.forEach(unionData -> {
                PeakStrongholdWarProto.PeakHoldUnionRoundEndMsg.Builder riseUpMsg = PeakStrongholdWarProto.PeakHoldUnionRoundEndMsg.newBuilder();
                riseUpMsg.setUnionId(unionData.getUnionId());
                riseUpMsg.setIsRiseUp(false);
                riseUpMsg.setGroupRank(0);
                riseUpMsg.setGroup(0);
                CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(this.cacheData.getRound() - 1, unionData.getUnionId());
                if (null != defendUnionData) {
                    riseUpMsg.setGroupRank(defendUnionData.getGroupRank());
                    riseUpMsg.setGroup(defendUnionData.getGroup());
                }
                riseUpMsg.setTotalRank(unionData.getRank());
                unionListMsg.addNotRiseUpUnions(riseUpMsg);
            });
        }

        for (CrossPeakStrongholdUnionData unionData : unionScoreRankList) {
            if (unionData.getLastRound() != this.cacheData.getRound()) {
                unionListMsg.addOutUnionIds(unionData.getUnionId());
            }
        }

        //下发名单
        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, unionGroup);
        for (long serverId : groupData.getServerSet()) {
            MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_PEAK_STRONGHOLD_ELIMINATE_UNION_LIST, unionListMsg));
            addWaitNotifyServerIds(Protocol.S_PEAK_STRONGHOLD_ELIMINATE_UNION_LIST, serverId);
        }
    }

    //设置排名并分组
    public void devideIntoGroupsByAbilityRank(PeakStrongholdTimeConfig timeConfig) {
        int needNum = Integer.parseInt(timeConfig.getParam());

        List<CrossPeakStrongholdUnionData> unionDataList = new ArrayList<>();
        int rank = 1;
        for (CrossUnionAbilityRankData rankData : abilityRankList) {
            if (rankData.getAbility().compareTo(BigInteger.ZERO) == 0) {
                continue;
            }
            UnionBaseInfo unionBaseInfo = rankData.getUnionBaseInfo();
            CrossPeakStrongholdUnionData unionData = getAndCreateUnionData(activityId, rankData.getUnionId());
            unionData.setCreateDefend(false);
            unionData.setRank(rank++);
            unionData.setLastRound(1);
            unionData.setUnionBaseInfo(unionBaseInfo);
            unionData.setAbility(rankData.getAbility());
            unionData.setUpdateOption();
            unionDataList.add(unionData);

            changeUnionActivityValue(unionData.getUnionId());

            if (--needNum <= 0) {
                break;
            }
        }
        //分组
        devideIntoGroups(unionDataList, null);
        for (CrossPeakStrongholdUnionData unionData : unionDataList) {
            this.waitCreateDefendUnions.add(unionData);
        }
        createDefendUnionByTimerTask();
        //赚钱排行分组后清理赚钱缓存
//        unionMemberAbilityMap.clear();
    }

    public void devideIntoGroupsByScoreRank(PeakStrongholdTimeConfig timeConfig) {
        int needNum = Integer.parseInt(timeConfig.getParam());
        List<CrossPeakStrongholdUnionData> unionDataList = new ArrayList<>();
        List<CrossPeakStrongholdUnionData> notRiseUpUnionDataList = new ArrayList<>();//未晋级的商会
        int rank = 1;
        for (CrossPeakStrongholdUnionData unionData : unionScoreRankList) {
            if (needNum > 0) {
                needNum--;
                unionData.setCreateDefend(false);
                unionData.setRank(rank++);
                unionData.setLastRound(this.cacheData.getRound());
                unionData.setUpdateOption();
                unionDataList.add(unionData);

            } else {
                if (unionData.getLastRound() == this.cacheData.getRound() - 1) {
                    //未晋级的商会
                    notRiseUpUnionDataList.add(unionData);
                } else {
                    break;
                }
            }
        }
        //分组
        devideIntoGroups(unionDataList, notRiseUpUnionDataList);
        for (CrossPeakStrongholdUnionData unionData : unionDataList) {
            this.waitCreateDefendUnions.add(unionData);
        }
        //创建
        createDefendUnionByTimerTask();
    }

    //释放旧回合的数据
    public void clearOldRoundData() {
        if (Config.isDebug()) {
            CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 释放旧回合数据,round<{}", this.cacheData.getRound());
        }
//        for (int round = 0; round < this.cacheData.getRound(); round++) {
//            defendUnionsMap.remove(round);
//            defendUnionsGroupMap.remove(round);
//        }
        if (this.cacheData.getRound() > 1) {
            this.abilityRankList.clear();
        }

        this.abilityRankMap.clear();
//        this.unionMemberAbilityMap.clear();
    }

    //定时创建据点
    public void createDefendUnionByTimerTask() {
        List<CrossPeakStrongholdUnionData> unionDatas = takeWaitCreateDefendUnion();
        for (CrossPeakStrongholdUnionData unionData : unionDatas) {
            CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(unionData.getLastRound(), unionData.getUnionId());
            if (null == defendUnionData) {
                defendUnionData = new CrossPeakStrongholdDefendUnionData(activityId, unionGroup, unionData.getLastRound(), unionData.getUnionId(), unionData.getGroup());
                defendUnionData.setDefendPatronsList(new ArrayList<>());
                addDefendUnionData(unionData.getLastRound(), defendUnionData);
            }
            defendUnionData.setRound(unionData.getLastRound());
            defendUnionData.setGroup(unionData.getGroup());
            defendUnionData.setScore(new BigInteger(unionData.getScore().toString()));
            defendUnionData.setRank(unionData.getScoreRank());

            unionData.setCreateDefend(true);
            unionData.setUpdateOption();

            removeWaitCreateDefendUnion(unionData);
            addRoundDamageRank(defendUnionData);

            CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 创建防守据点,round={},group={},unionId={}",
                    unionData.getLastRound(), unionData.getGroup(), unionData.getUnionId());

            //商会记录当前轮次的分组信息
            //add v5.4
            if (!unionData.getUnionDamageMap().containsKey(unionData.getLastRound())) {
                PeakStrongholdUnionDamage unionDamage = new PeakStrongholdUnionDamage();
                unionDamage.setRound(unionData.getLastRound());  //轮次
                unionDamage.setGroup(unionData.getGroup());      //分组
                unionData.getUnionDamageMap().put(unionDamage.getRound(), unionDamage);
                unionData.setUpdateOption();
            } else {
                PeakStrongholdUnionDamage unionDamage = unionData.getUnionDamageMap().get(unionData.getLastRound());
                unionDamage.setRound(unionData.getLastRound());  //轮次
                unionDamage.setGroup(unionData.getGroup());      //分组
                unionData.setUpdateOption();
            }
        }

        for(int groupId : unionRoundDamageRank.keySet()){
            updateRoundDamageRank(groupId);
        }
    }

    //更新成员防守数据
    public void updateMemberDefendInfo(PeakStrongholdWarProto.CrossPeakHoldDefendUserInfoTemp userInfoTemp) {
        synchronized (memberDamageRankList) {
            String unionId = userInfoTemp.getUnionId();
            long userId = userInfoTemp.getUserId();
            CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
            if (null == unionData) {
                //这里还没有商会数据是有问题的
                return;
            }
            unionData.setUpdateOption();
            PeakStrongholdUnionMemberInfo memberInfo = unionData.getMemberInfo(userId);
            if (!memberDamageRankList.contains(memberInfo)) {
                memberDamageRankList.add(memberInfo);
            }

            memberInfo.setDonateExp(userInfoTemp.getDonateExp());

            int defendAmount = 0;
            for (PeakStrongholdWarProto.CrossPeakHoldDefendPatronInfoTemp patronInfoTemp : userInfoTemp.getPatronInfosList()) {
                List<PeakStrongholdDefendPatrons> defendPatrons = unionData.getDefendPatrons().get(userId);
                if (null == defendPatrons) {
                    defendPatrons = new ArrayList<>();
                    unionData.getDefendPatrons().put(userId, defendPatrons);
                }
                PeakStrongholdDefendPatrons defendPatron = null;
                if (defendAmount < defendPatrons.size()) {
                    defendPatron = defendPatrons.get(defendAmount);
                } else {
                    defendPatron = new PeakStrongholdDefendPatrons();
                    defendPatron.setUserId(userId);
                    defendPatrons.add(defendPatron);
                }
                defendPatron.setSkinId(patronInfoTemp.getSkinId());
                defendPatron.setPatronsId(patronInfoTemp.getPatronsId());
                defendPatron.setLevel(patronInfoTemp.getLevel());
                defendPatron.setStageLv(patronInfoTemp.getStageLv());
                defendPatron.setEarnSpeed(new BigInteger(patronInfoTemp.getAbility()));

                defendAmount++;
            }
        }
    }

    //计算防守数据
    public void calcUnionDefendData() {
        int round = this.cacheData.getRound();
        Map<String, CrossPeakStrongholdDefendUnionData> defendUnionDataMap = defendUnionsMap.get(round);
        if (null == defendUnionDataMap) {
            return;
        }
        for (CrossPeakStrongholdDefendUnionData defendUnionData : defendUnionDataMap.values()) {
            String unionId = defendUnionData.getUnionId();
            CrossPeakStrongholdUnionData unionData = getUnionData(unionId);

            defendUnionData.setSilver(unionData.getTotalDonateSilver());
            defendUnionData.setSilverRank(unionData.getSilverRank());
            defendUnionData.getDefendPatronsList().clear();

            //据点星级
            PeakStrongholdBaseConfig baseConfig = config.getBaseConfigByExp(unionData.updateTotalDonateExp());
            if (null == baseConfig) {
                continue;//异常
            }
            defendUnionData.setStar(baseConfig.getLevel());
            int hpAdd = getHpAdd(unionId, defendUnionData.getStar());
            defendUnionData.setHpAdd(hpAdd);
            //防守血量
            BigInteger totalBlood = BigInteger.ZERO;
            List<PeakStrongholdDefendPatrons> defendPatronsList = unionData.getDefendPatronsList();
            if (defendPatronsList.isEmpty()) {
                //没有防守门客有问题
                continue;
            }
            int patronsNum = defendPatronsList.size();
            for (PeakStrongholdDefendPatrons defendPatrons : defendPatronsList) {
                BigInteger baseBlood = config.caluPatronsBlood(defendPatrons.getEarnSpeed());
                totalBlood = totalBlood.add(baseBlood);
            }

            totalBlood = totalBlood.add(totalBlood.multiply(BigInteger.valueOf(hpAdd)).divide(BigInteger.valueOf(1000)));

            for (PeakStrongholdDefendPatrons defendPatrons : defendPatronsList) {
                //每个门客的血量=商会据点总血量/防守门客的总数量
                BigInteger blood = totalBlood.divide(BigInteger.valueOf(patronsNum));
                defendPatrons.setCurBlood(new BigInteger(blood.toString()));
                defendPatrons.setTotalBlood(new BigInteger(blood.toString()));

                defendUnionData.getDefendPatronsList().add(defendPatrons.clone());
            }

            defendUnionData.setUpdateOption();

        }
    }

    /**
     * 获取淘汰赛血量加成
     */
    public int getHpAdd(String unionId, int level) {
        //千分比
        int unionBaseAdd = config.getUnionBaseAdd(level);
        int myRank = getUnionSilverRank(unionId);
        int hpAddByRank = config.getHpAddByRank(myRank);
        return unionBaseAdd + hpAddByRank;
    }

    /**
     * 获取银两捐献排行
     * -1:未上榜
     * 0：已淘汰
     *
     * @param unionUid
     * @return
     */
    public int getUnionSilverRank(String unionUid) {
        int myRank = -1;
        CrossPeakStrongholdUnionData unionData = getUnionData(unionUid);
        if (null != unionData) {
            if (unionData.getTotalDonateSilver().compareTo(BigInteger.ZERO) != 0) {
                return unionData.getSilverRank();
            }
        }
        return myRank;
    }

    //获得积分排行
    public int getUnionScoreRank(String unionUid) {
        int myRank = -1;
        CrossPeakStrongholdUnionData unionData = getUnionData(unionUid);
        if (null != unionData) {
            return unionData.getScoreRank();
        }

        return myRank;
    }

    //获得商会赚力排行
    @Deprecated
    public int getUnionAbilityRank(String unionId) {
        int myRank = -1;
        CrossUnionAbilityRankData rankData = getUnionAbilityRankData(unionId);
        if (null != rankData) {
            return rankData.getRank();
        }

        return myRank;
    }

    //获得个人伤害排行
    public int getMemberDamageRank(String unionId, long userId) {
        int myRank = -1;
        CrossPeakStrongholdUnionData unionData = unionDataMap.get(unionId);
        if (null != unionData) {
            PeakStrongholdUnionMemberInfo memberInfo = unionData.getMemberInfoMap().get(userId);
            if (null != memberInfo) {
                return memberInfo.getDamageRank();
            }
        }

        return myRank;
    }

    public void updateUnionBase(String unionId, long updateTime, UnionBaseInfo unionBaseInfo) {
        if (updateTime <= getLastUnionDeleteTime(unionId)) {
            return;
        }
        setLastUnionDeleteTime(unionId, updateTime);

        if (!unionDataMap.containsKey(unionId)) {
            return;
        }

        CrossPeakStrongholdUnionData unionData = unionDataMap.get(unionId);
        if (null == unionData) {
            return;
        }

        unionData.setUnionBaseInfo(unionBaseInfo);

        updateNowScoreRank();

        changeUnionActivityValue(unionId);
    }

    //有商会解散
    @Deprecated
    public void deleteUnion(String unionId, long updateTime) {
        if (!canChangeUnion()) {
            return;
        }

        if (getLastUnionUpdateTime(unionId) > 0) {
            return;
        }
        deleteUnionAbilityRank(unionId);
    }

    private boolean canChangeUnion() {
        if (this.cacheData.getStageType() != ePeakStrongholdStageType.Registration.getValue() ||
                this.cacheData.getStageType() != ePeakStrongholdStageType.WaitUpdateEnd.getValue()) {
            return true;
        }
        return false;
    }

//    @Deprecated
//    public void deleteUnionMember(String unionId, long userId) {
//        if (!canChangeUnion()) {
//            return;
//        }
//        CrossUnionAbilityCacheData abilityCacheData = getUnionAbilityCacheData(unionId);
//        if (null == abilityCacheData) {
//            return;
//        }
//        abilityCacheData.getUserAbility().remove(userId);
//        abilityCacheData.setUpdateOption();
//
//        CrossUnionAbilityRankData unionAbilityRankData = getUnionAbilityRankData(unionId);
//        if (null != unionAbilityRankData) {
//            BigInteger total = BigInteger.ZERO;
//            for (BigInteger ability : abilityCacheData.getUserAbility().values()) {
//                total = total.add(ability);
//            }
//            unionAbilityRankData.setAbility(total);
//            unionAbilityRankChange();
//            //abilityRankChangeMark = true;
//        }
//    }

//    private CrossUnionAbilityCacheData getUnionAbilityCacheData(String unionId) {
//        CrossUnionAbilityCacheData cacheData = this.unionMemberAbilityMap.get(unionId);
//        if (null == cacheData) {
//            synchronized (unionMemberAbilityMap) {
//                cacheData = this.unionMemberAbilityMap.get(unionId);
//                if (null == cacheData) {
//                    cacheData = new CrossUnionAbilityCacheData();
//                    cacheData.setActivityId(activityId);
//                    cacheData.setInsertOption();
//                    cacheData.setUnionId(unionId);
//                    cacheData.setUserAbility(new ConcurrentHashMap<>());
//                    this.unionMemberAbilityMap.put(unionId, cacheData);
//                }
//            }
//        }
//        return cacheData;
//    }

    //没上传完的继续去上传
    private Map<Long, List<String>> serverUnionMap = new ConcurrentHashMap<>();

    private void addUnSuccessUnion(long serverId, String unionId) {
        if (!serverUnionMap.containsKey(serverId)) {
            synchronized (serverUnionMap) {
                if (!serverUnionMap.containsKey(serverId)) {
                    serverUnionMap.put(serverId, new ArrayList<>());
                }
            }
        }
        synchronized (serverUnionMap.get(serverId)) {
            if (serverUnionMap.get(serverId).contains(unionId)) {
                serverUnionMap.get(serverId).add(unionId);
            }
        }
    }

//    @Deprecated
//    public void updateTotalAbility(PeakStrongholdWarProto.CrossPeakHoldUnionMemberAbilityResp respMsg) {
//        for (PeakStrongholdWarProto.PeakHoldUnionAbilityTemp unionAbilityTemp : respMsg.getUnionAbilityList()) {
//            String unionId = unionAbilityTemp.getUnionId();
//            CrossUnionAbilityCacheData cacheData = getUnionAbilityCacheData(unionId);
//            for (PeakStrongholdWarProto.PeakHoldMemberAbilityTemp memberAbilityTemp : unionAbilityTemp.getMemberInfoList()) {
//                //更新个人门客总赚钱
//                cacheData.updateUserAbility(memberAbilityTemp.getUserId(), new BigInteger(memberAbilityTemp.getTotalAbility()));
//            }
//
////            if (cacheData.getUserAbility().size() != unionAbilityTemp.getMemberIdsCount()) {
////                //商会成员数量对不上,没缓存完
////                CrossPeakStrongholdMgr.getLogger().error("巅峰据点{},商会{},成员数据还没缓存完1，没有数据生成",activityId,unionAbilityTemp.getUnionId());
////                //没对上还要一直去拉，不然就没了，报名期排行榜没有数据
////                addUnSuccessUnion(unionAbilityTemp.getUnionBaseInfo().getServerId(),unionAbilityTemp.getUnionId());
////            }
//
//            for (long userId : unionAbilityTemp.getMemberIdsList()) {
//                if (!cacheData.getUserAbility().containsKey(userId)) {
//                    //该商会还有成员不在缓存里,等待全部缓存完
//                    //商会成员数量对不上,没缓存完
//                    CrossPeakStrongholdMgr.getLogger().error("巅峰据点{},商会{},成员数据还没缓存完2，没有数据生成",activityId,unionAbilityTemp.getUnionId());
//                    //没对上还要一直去拉，不然就没了，报名期排行榜没有数据
//                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
//                    if(userBaseInfo != null && this.cacheData.getStageType() == ePeakStrongholdStageType.Registration.getValue()){
//                        addUnSuccessUnion(userBaseInfo.getServerId(), unionAbilityTemp.getUnionId());
//                    }
//                }
//            }
//
//            //累计总赚钱
//            BigInteger total = BigInteger.ZERO;
//            for (BigInteger ability : cacheData.getUserAbility().values()) {
//                total = total.add(ability);
//            }
//            //更新到门客赚钱排行
//            UnionBaseInfo unionBaseInfo = CrossRankPb.parseUnionBaseInfo(unionAbilityTemp.getUnionBaseInfo());
//            updateUnionAbilityRank(unionId, unionBaseInfo, total);
//        }
//    }

    //淘汰赛结束积分结算
    public void socreRankSettle() {
        //积分结算
        PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), this.cacheData.getRound());
        for (int groupId : unionRoundDamageRank.keySet()) {
            updateRoundDamageRank(groupId);
        }
        for (List<CrossPeakStrongholdDefendUnionData> unionDatas : unionRoundDamageRank.values()) {
            for (int i = 0; i < unionDatas.size(); i++) {
                int rank = i + 1;
                int scoreAdd = timeConfig.getRankScore(rank);
                CrossPeakStrongholdDefendUnionData defendUnionData = unionDatas.get(i);
                CrossPeakStrongholdUnionData unionData = getAndCreateUnionData(activityId, defendUnionData.getUnionId());
                BigInteger totalScore = unionData.getScore();
                totalScore = totalScore.add(BigInteger.valueOf(scoreAdd));
                unionData.setScore(totalScore);
                BigInteger totalGroupScore = unionData.getTotalGroupScore().add(defendUnionData.getGroupScore());
                unionData.setTotalGroupScore(totalGroupScore);

                if (Config.isDebug()) {
                    CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 {}回合结束积分结算, 商会{}组{}内排名{}获得排名积分{}",
                            this.cacheData.getRound(), unionData.getUnionId(), defendUnionData.getGroup(), rank, scoreAdd);
                }
                changeUnionActivityValue(unionData.getUnionId());

                //记录商会积分与伤害
                //v5.4 add
                if (unionData.getUnionDamageMap().containsKey(defendUnionData.getRound())) {
                    PeakStrongholdUnionDamage unionDamage = unionData.getUnionDamageMap().get(defendUnionData.getRound());
                    unionDamage.setScore(scoreAdd);
                    unionDamage.setRankInGroup(rank);
                    BigInteger damage = BigInteger.ZERO;
                    for (Map.Entry<String, Map<Long, BigInteger>> entry : defendUnionData.getAttackUnionMap().entrySet()) {
                        for (Map.Entry<Long, BigInteger> integerEntry : entry.getValue().entrySet()) {
                            damage = damage.add(integerEntry.getValue());
                        }
                    }
                    unionDamage.setDamage(damage.toString());
                    unionDamage.setGroupScore(defendUnionData.getGroupScore().toString());
                    unionData.setUpdateOption();
                }
            }
        }
        unionRoundDamageRank.clear();

        unionScoreRankChangeSort();
    }


    public void timerSync(){
        syncCondition();
        syncUnionRank();
    }

    private void syncUnionRank(){
        List<String> syncTempList = new ArrayList<>();
        if(unionScoreSyncList.size() > 0){
            synchronized (unionScoreSyncList){
                syncTempList = new ArrayList<>(unionScoreSyncList);
            }
            unionScoreSyncList.clear();
        }
        if(syncTempList.size() > 0){
            String rankKey = String.valueOf(eGamePlayerEventType.PeakStrongHoldUnionIntegralRank.getValue());
            long currentTime = DateHelper.getCurrentTime();

//            PeakStrongholdWarProto.CrossPeakHoldGetUnionReqMsg.Builder syncMsg = PeakStrongholdWarProto.CrossPeakHoldGetUnionReqMsg.newBuilder();
//            syncMsg.setActivityId(activityId);
//            syncMsg.addAllUnionId(syncTempList);
//            syncMsg.setUnionGroup(unionGroup);
//            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C3_PEAK_STRONGHOLD_GET_UNION_REQ, syncMsg);
//            List<Long> serverIdList = config.getActivityInfo().getServerIdList();
//            MessageHelper.sendPacket(serverIdList.get(randomHelper.next(0,serverIdList.size())), 0, pbMsg);

            UnionActivityGroup unionGroupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, unionGroup);
            if (unionGroupData == null) {
                PeakSeacraftMgr.getLogger().error("找不到商会分组数据,activityId={},unionGroup={}", activityId, unionGroup);
                return;
            }
            for (String unionId : syncTempList) {
                CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
                if (unionData == null) {
                    continue;
                }

                UnionActivityGroupUnion groupUnion = unionGroupData.getGroupUnion(unionId);
                if (groupUnion == null) {
                    PeakSeacraftMgr.getLogger().error("商会分组找不到商会, activityId={}, unionGroup={}, unionId={}", activityId, unionGroup, unionId);
                    continue;
                }
                ConcurrentHashMap<Long, Integer> memberMap = new ConcurrentHashMap<>();
                for (UnionActivityGroupUser groupUser : groupUnion.getUserMap().values()) {
                    memberMap.put(groupUser.getUserId(), groupUser.getPosition());
                }
                UnionBaseInfo unionBaseInfo = unionData.getUnionBaseInfo();
                unionBaseInfo.setTotalPatronsAbility(unionData.getAbility());
                unionBaseInfo.setParamValue(unionData.getTotalGroupScore());
                String rankParamValue = unionData.parseUnionRankParamValue();
                CrossYRankMgr.unionRankChange(activityId, unionGroup, rankKey, unionData.getUnionId(), unionBaseInfo, memberMap, UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, currentTime, rankParamValue);
            }
        }
    }

    private void syncCondition(){
        List<CrossConditionSyncData> syncTempList = new ArrayList<>();
        if(conditionSyncDataList.size() > 0){
            synchronized (conditionSyncDataList){
                syncTempList = new ArrayList<>(conditionSyncDataList);
            }
            conditionSyncDataList.clear();
        }
        Map<Long,List<CrossConditionSyncData>> syncMap = new ConcurrentHashMap<>();
        if(syncTempList.size() > 0){
            for(CrossConditionSyncData data : syncTempList){
                if(!syncMap.containsKey(data.getServerId())){
                    syncMap.put(data.getServerId(),new ArrayList<>());
                }
                syncMap.get(data.getServerId()).add(data);
            }
        }
        if(syncMap.size() > 0){
            Map<Long, TwinsProto.SimpleCrossConditionSyncMsg.Builder> serverSyncMap = new ConcurrentHashMap<>();
            for(long serverId : syncMap.keySet()){
                TwinsProto.SimpleCrossConditionSyncMsg.Builder msg = TwinsProto.SimpleCrossConditionSyncMsg.newBuilder();
                msg.setActivityId(config.getActivityInfo().getActivityId());
                for(CrossConditionSyncData data : syncMap.get(serverId)){
                    TwinsProto.SimpleCrossConditionMsg.Builder cdMsg = TwinsProto.SimpleCrossConditionMsg.newBuilder();
                    cdMsg.setUserId(data.getUserId());
                    cdMsg.setType(data.getType());
                    cdMsg.setValue(data.getValue().toString());
                    cdMsg.setParam(data.getParam());
                    msg.addSyncData(cdMsg);
                }
                serverSyncMap.put(serverId,msg);
            }
            for(long serverId : serverSyncMap.keySet()){
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_TWINS_CROSS_CONDITION_SYNC, serverSyncMap.get(serverId));
                MessageHelper.sendPacket(serverId, 0, pbMsg);
            }
        }
    }

    private void addNeedSyncCondition(CrossConditionSyncData data){
        synchronized (conditionSyncDataList){
            if(!conditionSyncDataList.contains(data)){
                conditionSyncDataList.add(data);
            }
        }
    }

    public void changeUnionActivityValue(String unionUid) {
        synchronized (unionScoreSyncList){
            if(!unionScoreSyncList.contains(unionUid)){
                unionScoreSyncList.add(unionUid);
            }
        }
    }


    @Deprecated
    public void unionRankUpdate(PeakStrongholdWarProto.CrossPeakHoldGetUnionRespMsg reqMsg) {
        CrossPeakStrongholdMgr.getLogger().error("巅峰据点{},更新商会排行,{}个商会", activityId, reqMsg.getUnionCount());
        String rankKey = String.valueOf(eGamePlayerEventType.PeakStrongHoldUnionIntegralRank.getValue());
        long currentTime = DateHelper.getCurrentTime();
        for (PeakStrongholdWarProto.PeakStrongHoldUnionMsg unionMsg : reqMsg.getUnionList()) {
            CrossPeakStrongholdUnionData unionData = getUnionData(unionMsg.getUnionUid());
            if (unionData != null) {
                ConcurrentHashMap<Long, Integer> memberMap = new ConcurrentHashMap<>();
                for (PeakStrongholdWarProto.PeakStrongHoldUnionMemberMsg memberMsg : unionMsg.getMemberList()) {
                    memberMap.put(memberMsg.getUserId(), memberMsg.getPosition());
                }
                UnionBaseInfo unionBaseInfo = UnionBasePb.parseUnionBaseInfo(unionMsg.getUnionInfo());
                if (unionBaseInfo != null) {
                    unionBaseInfo.setTotalPatronsAbility(unionData.getAbility());
                    unionBaseInfo.setParamValue(unionData.getTotalGroupScore());
                    String rankParamValue = unionData.parseUnionRankParamValue();
//                    CrossUnionActivityDataMgr.changeUserData(
//                            activityId, eGamePlayerEventType.PeakStrongHoldUnionIntegralRank.getValue(), unionData.getScore(), unionMsg.getUnionUid()
//                            , UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, memberMap, unionData.getUnionBaseInfo().getServerId(), unionBaseInfo);

                    CrossYRankMgr.unionRankChange(activityId, unionGroup, rankKey, unionData.getUnionId(), unionData.getUnionBaseInfo(), memberMap, UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, currentTime, rankParamValue);
                }
            }
        }
    }

    //竞猜结束了,关亚季军
    private void guessChampionResult(){
        initGamebleRight(0);
        long nowTime = System.currentTimeMillis();
        //决赛结束
        if(nowTime >= config.getRoundEndTime(config.getTotalRound())) {
            List<String> championUnionIdList = new ArrayList<>();
            //前三名
            for (int i = 0; i < unionScoreRankList.size() && i < 3; i++) {
                championUnionIdList.add(unionScoreRankList.get(i).getUnionId());
            }
            //触发所有人，都有显示每个档位的猜对人数
            UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, unionGroup);
            for (long serverId : groupData.getServerSet()) {
                CrossConditionSyncData data = new CrossConditionSyncData();
                data.setServerId(serverId);
                data.setUserId(0);
                data.setType(eGamePlayerEventType.PeakStrongHoldGuessChampion.getValue());
                data.setValue(BigInteger.valueOf(-1));
                data.setParam(getGamebleRightCountString(0));
                addNeedSyncCondition(data);
            }

            for (long userId : userFinalsGuessMap.keySet()) {
                List<String> guessUnionList = userFinalsGuessMap.get(userId);
                List<String> guessRightUnionList = new ArrayList<>();
                //猜中分数
                int guessScore = 0;
                boolean guess1 = false;
                boolean guess2 = false;
                boolean guess3 = false;
                for(int i = 0; i < 3 ; i++){
                    if(i >= championUnionIdList.size())continue;
                    String winUnionId = championUnionIdList.get(i);
                    if(i == 0){
                        if(guessUnionList.indexOf(winUnionId) == 0){
                            guess1 = true;
                            guessRightUnionList.add(winUnionId);
                        }
                    }else if(i == 1){
                        if(guessUnionList.indexOf(winUnionId) == 1){
                            guess2 = true;
                            guessRightUnionList.add(winUnionId);
                        }
                    } else if (i == 2) {
                        if(guessUnionList.indexOf(winUnionId) == 2){
                            guess3 = true;
                            guessRightUnionList.add(winUnionId);
                        }
                    }
                }
                //都猜对4分
                if(guess1 && guess2 && guess3){
                    guessScore = 4;
                }else if(guess1){
                    guessScore = 3;
                }else if(guess2){
                    guessScore = 2;
                }else if(guess3){
                    guessScore = 1;
                }
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
                if(userBaseInfo == null)continue;
                CrossConditionSyncData data = new CrossConditionSyncData();
                data.setServerId(userBaseInfo.getServerId());
                data.setUserId(userId);
                data.setType(eGamePlayerEventType.PeakStrongHoldGuessChampion.getValue());
                data.setValue(BigInteger.valueOf(guessScore));
                data.setParam(getGamebleRightCountString(0));
                addNeedSyncCondition(data);
                CrossAutoLogMgr.add(new LogCrossPeakHoldGuess(activityId, userId, 0,
                        StringUtils.listToString(guessUnionList, ","),
                        StringUtils.listToString(guessRightUnionList, ",")));
            }
        }
    }

    public void getGambleUser(long serverId, long userId, PeakStrongholdWarProto.PeakHoldGetGambleUserReqMsg reqMsg) {
        PeakStrongholdWarProto.PeakHoldGetGambleUserRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakHoldGetGambleUserRespMsg.newBuilder();
        respMsg.setCount(0);
        Map<Integer,List<Long>> userMap = rightGuessUserMap.get(reqMsg.getTimeId());
        if(userMap.size() > 0){
            if(userMap.containsKey(reqMsg.getRight())){
                List<Long> userIdList = userMap.get(reqMsg.getRight());
                respMsg.setCount(userIdList.size());
                int index = reqMsg.getIndex();
                int count = 0;
                for(int i = index ; i < userIdList.size();i++){
                    if(count == 10){
                        break;
                    }
                    long gambleUserId = userIdList.get(i);
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(gambleUserId);
                    if(userBaseInfo == null)continue;
                    PeakStrongholdWarProto.PeakHoldGambleUserMsg.Builder userMsg = PeakStrongholdWarProto.PeakHoldGambleUserMsg.newBuilder();
                    userMsg.setUserId(gambleUserId);
                    userMsg.setNickName(userBaseInfo.getNickName());
                    userMsg.setServerId(userBaseInfo.getServerId());
                    userMsg.setIndex(i);
                    respMsg.addUser(userMsg);
                    count++;
                }
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_GET_GAMBLE_USER, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }


    private String getGamebleRightCountString(int timeId){
        Map<Integer,Integer> rightCountUserCountMap = rightGuessCountMap.get(timeId);
        String retStr = timeId + "|";
        //轮次|才对次数=人次;才对次数=人次;才对次数=人次;才对次数=人次;才对次数=人次
        for(int rightCount : rightCountUserCountMap.keySet()){
            retStr = retStr + rightCount + "=" + rightCountUserCountMap.get(rightCount) + ";";
        }
        return retStr.substring(0,retStr.length() - 1);
    }


    //猜对个数的合集
    private void initGamebleRight(int timeId){
        rightGuessCountMap.put(timeId,new ConcurrentHashMap<>());
        rightGuessUserMap.put(timeId,new ConcurrentHashMap<>());
        if(timeId == 0){
            if(userFinalsGuessMap.size() == 0){
                return;
            }
            List<String> championUnionIdList = new ArrayList<>();
            //前三名
            for(int i = 0;i < unionScoreRankList.size() && i < 3;i++){
                championUnionIdList.add(unionScoreRankList.get(i).getUnionId());
            }
            for(long userId : userFinalsGuessMap.keySet()){
                List<String> guessUnionList = userFinalsGuessMap.get(userId);
                //猜中分数
                int guessScore = 0;
                boolean guess1 = false;
                boolean guess2 = false;
                boolean guess3 = false;
                for(int i = 0; i < 3 ; i++){
                    String winUnionId = championUnionIdList.get(i);
                    if(i == 0){
                        if(guessUnionList.indexOf(winUnionId) == 0){
                            guess1 = true;
                        }
                    }else if(i == 1){
                        if(guessUnionList.indexOf(winUnionId) == 1){
                            guess2 = true;
                        }
                    } else if (i == 2) {
                        if(guessUnionList.indexOf(winUnionId) == 2){
                            guess3 = true;
                        }
                    }
                }
                //都猜对4分
                if(guess1 && guess2 && guess3){
                    guessScore = 4;
                }else if(guess1){
                    guessScore = 3;
                }else if(guess2){
                    guessScore = 2;
                }else if(guess3){
                    guessScore = 1;
                }
                rightGuessCountMap.get(timeId).put(guessScore,rightGuessCountMap.get(timeId).getOrDefault(guessScore,0) + 1);
                if(!rightGuessUserMap.get(timeId).containsKey(guessScore)){
                    rightGuessUserMap.get(timeId).put(guessScore,new ArrayList<>());
                }
                rightGuessUserMap.get(timeId).get(guessScore).add(userId);
            }
        }else{
            //第一轮竞猜结束，也就是倒是第二场结束
            if(!userSelectGuessMap.containsKey(timeId) || userSelectGuessMap.get(timeId).size() == 0){
                return;
            }
            PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(timeId);
            int finalUnionCount = Integer.valueOf(timeConfig.getParam());
            List<String> passUnionIdList = new ArrayList<>();
            for(int i = 0;i < unionScoreRankList.size() && i < finalUnionCount;i++){
                passUnionIdList.add(unionScoreRankList.get(i).getUnionId());
            }
            for(long userId : userSelectGuessMap.get(timeId).keySet()){
                List<String> guessUnionList = userSelectGuessMap.get(timeId).get(userId);
                //猜中几个
                int guessRightCount = 0;
                for(String userGuessUnionId : guessUnionList){
                    if(passUnionIdList.contains(userGuessUnionId)){
                        guessRightCount++;
                    }
                }
                rightGuessCountMap.get(timeId).put(guessRightCount,rightGuessCountMap.get(timeId).getOrDefault(guessRightCount,0) + 1);
                if(!rightGuessUserMap.get(timeId).containsKey(guessRightCount)){
                    rightGuessUserMap.get(timeId).put(guessRightCount,new ArrayList<>());
                }
                rightGuessUserMap.get(timeId).get(guessRightCount).add(userId);
            }
        }
    }

    //竞猜结束了 前八名
    private void guessWinResult(int timeId){
        initGamebleRight(timeId);
        //第一轮竞猜结束，也就是倒是第二场结束
        PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(timeId);
        int finalUnionCount = Integer.valueOf(timeConfig.getParam());
        List<String> passUnionIdList = new ArrayList<>();
        for (int i = 0; i < unionScoreRankList.size() && i < finalUnionCount; i++) {
            passUnionIdList.add(unionScoreRankList.get(i).getUnionId());
        }
        if (!userSelectGuessMap.containsKey(timeId)) {
            return;
        }
        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, unionGroup);
        for (long serverId : groupData.getServerSet()) {
            CrossConditionSyncData data = new CrossConditionSyncData();
            data.setServerId(serverId);
            data.setUserId(0);
            data.setType(eGamePlayerEventType.PeakStrongHoldGuessWin.getValue());
            data.setValue(BigInteger.valueOf(-1));
            data.setParam(getGamebleRightCountString(timeId));
            addNeedSyncCondition(data);
        }
        for (long userId : userSelectGuessMap.get(timeId).keySet()) {
            List<String> guessUnionList = userSelectGuessMap.get(timeId).get(userId);
            List<String> guessRightUnionList = new ArrayList<>();
            //猜中几个
            int guessRightCount = 0;
            for(String userGuessUnionId : guessUnionList){
                if(passUnionIdList.contains(userGuessUnionId)){
                    guessRightCount++;
                    guessRightUnionList.add(userGuessUnionId);
                }
            }
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
            if(userBaseInfo == null)continue;
            CrossConditionSyncData data = new CrossConditionSyncData();
            data.setServerId(userBaseInfo.getServerId());
            data.setUserId(userId);
            data.setType(eGamePlayerEventType.PeakStrongHoldGuessWin.getValue());
            data.setValue(BigInteger.valueOf(guessRightCount));
            data.setParam(getGamebleRightCountString(timeId));
            addNeedSyncCondition(data);
            CrossAutoLogMgr.add(new LogCrossPeakHoldGuess(activityId, userId, timeId,
                    StringUtils.listToString(guessUnionList, ","),
                    StringUtils.listToString(guessRightUnionList, ",")));
        }
    }

    /**
     * 获取对应的胜利的商会
     * @param timeId 0决赛 100001等等对应轮次先这样
     * @return
     */
    private List<String> guessPassUnionList(int timeId){
        long nowTime = System.currentTimeMillis();
        List<String> unionIdList = new ArrayList<>();
        if(timeId == 0){
            if(nowTime >= config.getRoundEndTime(config.getTotalRound())){
                for(int i = 0;i < unionScoreRankList.size() && i < 3;i++){
                    unionIdList.add(unionScoreRankList.get(i).getUnionId());
                }
            }
        }else{
            PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(timeId);
            int finalUnionCount = Integer.valueOf(timeConfig.getParam());
            for(int i = 0;i < unionScoreRankList.size() && i < finalUnionCount;i++){
                unionIdList.add(unionScoreRankList.get(i).getUnionId());
            }
        }
        return unionIdList;
    }


    //生成竞猜队伍
    private void guessUnionMake(int timeId){
        long nowTime = System.currentTimeMillis();
        if(timeId == 0){
            //多少个商会猜冠亚军
            PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), config.getTotalRound()-1);
            int finalUnionCount = Integer.valueOf(timeConfig.getParam());
            //决出最后的几个队伍了才初始化，多一分钟
            if(userFinalsGuessCountMap.size() == 0 && nowTime > config.getRoundEndTime(config.getTotalRound() - 1) + 60000){
                synchronized (userFinalsGuessCountMap){
                    if(userFinalsGuessCountMap.size() == 0 && nowTime > config.getRoundEndTime(config.getTotalRound() - 1) + 60000){
                        if(userFinalsGuessCountMap.size() == 0){
                            for(int i = 0;i < unionScoreRankList.size() && i < finalUnionCount;i++){
                                CrossPeakStrongholdUnionData unionData = unionScoreRankList.get(i);
                                userFinalsGuessCountMap.put(unionData.getUnionId(),0);
                            }
                            for(List<String> unionIdList : userFinalsGuessMap.values()){
                                for(String unionId : unionIdList){
                                    if(userFinalsGuessCountMap.containsKey(unionId)){
                                        userFinalsGuessCountMap.put(unionId,userFinalsGuessCountMap.get(unionId) + 1);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }else{
            //猜八强的
            if(!userSelectGuessCountMap.containsKey(timeId) || userSelectGuessCountMap.get(timeId).size() == 0){
                synchronized (userSelectGuessCountMap){
                    if(!userSelectGuessCountMap.containsKey(timeId) || userSelectGuessCountMap.get(timeId).size() == 0){
                        if(!userSelectGuessCountMap.containsKey(timeId)){
                            userSelectGuessCountMap.put(timeId,new ConcurrentHashMap<>());
                        }
                        if(!userSelectGuessMap.containsKey(timeId)){
                            userSelectGuessMap.put(timeId,new ConcurrentHashMap<>());
                        }
                        PeakStrongholdTimeConfig timeConfig = config.getTimeConfigForward(timeId);
                        int unionCount = Integer.valueOf(timeConfig.getParam());
                        if(userSelectGuessCountMap.get(timeId).size() == 0){
                            for(int i = 0;i < unionScoreRankList.size() && i < unionCount;i++){
                                CrossPeakStrongholdUnionData unionData = unionScoreRankList.get(i);
                                userSelectGuessCountMap.get(timeId).put(unionData.getUnionId(),0);
                            }
                            for(List<String> unionIdList : userSelectGuessMap.get(timeId).values()){
                                for(String unionId : unionIdList){
                                    if(userSelectGuessCountMap.get(timeId).containsKey(unionId)){
                                        userSelectGuessCountMap.get(timeId).put(unionId,userSelectGuessCountMap.get(timeId).get(unionId) + 1);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public CrossPeakStrongholdUserGuessData getUserGuessData(long userId){
        if(!userGuessDataMap.containsKey(userId)){
            synchronized (userGuessDataMap){
                CrossPeakStrongholdUserGuessData userData = new CrossPeakStrongholdUserGuessData(activityId, unionGroup, userId);
                userGuessDataMap.put(userId,userData);
            }
        }
        return userGuessDataMap.get(userId);
    }

    //添加玩家的竞猜信息
    private void guessBattle(long userId,int timeId , List<String> unionIdList){
        CrossPeakStrongholdUserGuessData userData = getUserGuessData(userId);
        if(timeId == 0){
            userFinalsGuessMap.put(userId,unionIdList);
            userData.setGuessFinalsMap(new ArrayList<>(unionIdList));
            synchronized (userFinalsGuessCountMap){
                userFinalsGuessCountMap.clear();
            }
        }else{
            userSelectGuessMap.get(timeId).put(userId,unionIdList);
            synchronized (userSelectGuessCountMap){
                userSelectGuessCountMap.get(timeId).clear();
            }
            Map<Integer, List<String>> guessWinMap = userData.getGuessWinMap();
            guessWinMap.put(timeId,new ArrayList<>(unionIdList));
            userData.setGuessWinMap(guessWinMap);
        }
    }

    private List<Integer> timeIdList = new ArrayList<>();

    private List<Integer> getGuessTimeIdList(){
        if(timeIdList.size() == 0){
            synchronized (timeIdList){
                if(timeIdList.size() == 0){
                    List<ActivityConditionInfo> conditionList = ActivityMgr.getActivityConditionInfoList(activityId);
                    List<Integer> tempTimeIdList = new ArrayList<>();
                    for(ActivityConditionInfo conditionInfo : conditionList){
                        if(conditionInfo.getType() == eGamePlayerEventType.PeakStrongHoldGuessWin.getValue()){
                            int conditionTimeId = conditionInfo.getParamList().get(2).intValue();
                            if(!tempTimeIdList.contains(conditionTimeId)){
                                tempTimeIdList.add(conditionTimeId);
                            }
                        }
                    }
                    if(tempTimeIdList.size() > 0){
                        timeIdList = tempTimeIdList;
                    }
                }
            }
        }
        return timeIdList;
    }

    public void login(long serverId, long userId, PeakStrongholdWarProto.CrossPeakHoldUserLoginReqMsg reqMsg) {
        long nowTime = System.currentTimeMillis();
        List<Integer> timeIdList = getGuessTimeIdList();
        CrossPeakStrongholdUserGuessData userData = getUserGuessData(userId);
        Map<Integer, List<String>> guessWinMap = new ConcurrentHashMap<>(userData.getGuessWinMap());
        for(int timeId : timeIdList){
            long configEndTime = config.getTimeConfigEndTime(timeId);
            if(nowTime > configEndTime){
                PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(timeId);
                int finalUnionCount = Integer.valueOf(timeConfig.getParam());
                List<String> passUnionIdList = new ArrayList<>();
                for(int i = 0;i < unionScoreRankList.size() && i < finalUnionCount;i++){
                    passUnionIdList.add(unionScoreRankList.get(i).getUnionId());
                }
                int guessRightCount = 0;
                if(guessWinMap.containsKey(timeId)){
                    List<String> guessUnionList = guessWinMap.get(timeId);
                    for(String userGuessUnionId : guessUnionList){
                        if(passUnionIdList.contains(userGuessUnionId))guessRightCount++;
                    }
                }else{
                    guessRightCount = -1;
                }

                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
                if(userBaseInfo == null)continue;
                CrossConditionSyncData data = new CrossConditionSyncData();
                data.setServerId(userBaseInfo.getServerId());
                data.setUserId(userId);
                data.setType(eGamePlayerEventType.PeakStrongHoldGuessWin.getValue());
                data.setValue(BigInteger.valueOf(guessRightCount));
                data.setParam(getGamebleRightCountString(timeId));
                addNeedSyncCondition(data);
            }
        }
        if(nowTime >= config.getRoundEndTime(config.getTotalRound())){
            List<String> championUnionIdList = new ArrayList<>();
            //前三名
            for(int i = 0;i < unionScoreRankList.size() && i < 3;i++){
                championUnionIdList.add(unionScoreRankList.get(i).getUnionId());
            }
            List<String> guessUnionList = new ArrayList<>(userData.getGuessFinalsMap());
            //猜中分数
            int guessScore = 0;
            //有进行竞猜
            if(guessUnionList.size() > 0){
                boolean guess1 = false;
                boolean guess2 = false;
                boolean guess3 = false;
                for(int i = 0; i < 3 ; i++){
                    String winUnionId = championUnionIdList.get(i);
                    if(i == 0){
                        if(guessUnionList.indexOf(winUnionId) == 0){
                            guess1 = true;
                        }
                    }else if(i == 1){
                        if(guessUnionList.indexOf(winUnionId) == 1){
                            guess2 = true;
                        }
                    } else if (i == 2) {
                        if(guessUnionList.indexOf(winUnionId) == 2){
                            guess3 = true;
                        }
                    }
                }
                //都猜对4分
                if(guess1 && guess2 && guess3){
                    guessScore = 4;
                }else if(guess1){
                    guessScore = 3;
                }else if(guess2){
                    guessScore = 2;
                }else if(guess3){
                    guessScore = 1;
                }
            }else{
                guessScore = -1;
            }

            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
            if(userBaseInfo != null){
                CrossConditionSyncData data = new CrossConditionSyncData();
                data.setServerId(userBaseInfo.getServerId());
                data.setUserId(userId);
                data.setType(eGamePlayerEventType.PeakStrongHoldGuessChampion.getValue());
                data.setValue(BigInteger.valueOf(guessScore));
                data.setParam(getGamebleRightCountString(0));
                addNeedSyncCondition(data);
            }
        }
    }

    //竞猜队伍获胜
    public void guess(long serverId, long userId, PeakStrongholdWarProto.PeakStrongholdGuessReqMsg reqMsg) {
        PeakStrongholdWarProto.PeakStrongholdGuessRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakStrongholdGuessRespMsg.newBuilder();
        respMsg.setRet(0);
        int timeId = reqMsg.getType();
        PeakStrongholdTimeConfig finalTimeConfig = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), config.getTotalRound());
        if(finalTimeConfig.getTimeId() == timeId){
            timeId = 0;
        }
        long nowTime = System.currentTimeMillis();
        if(timeId != 0){
            PeakStrongholdTimeConfig forwardTimeConfig = config.getTimeConfigForward(timeId);
            PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(timeId);
            long lastEndTime = config.getTimeConfigEndTime(forwardTimeConfig.getTimeId());
            long nowBeginTime = config.getTimeConfigBeginTime(timeId);
            if(nowTime < lastEndTime || nowTime > nowBeginTime){
                respMsg.setRet(GameErrorCode.E_PEAK_HOLD_GUESS_TIME);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_GUESS, respMsg);
                MessageHelper.sendPacket(serverId, userId, pbMsg);
                return;
            }
            //晋级赛前八的商会,可能会没有前八个玩家吧，如果比赛一开始就不够八个商会就不判断等于8了
            if(reqMsg.getUnionIdCount() > Integer.valueOf(timeConfig.getParam())){
                respMsg.setRet(GameErrorCode.E_PEAK_HOLD_GUESS_UNION_COUNT);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_GUESS, respMsg);
                MessageHelper.sendPacket(serverId, userId, pbMsg);
                return;
            }
            guessBattle(userId,timeId,reqMsg.getUnionIdList());
        }else{
            PeakStrongholdTimeConfig timeConfigForward = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), config.getTotalRound()-1);
            PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), config.getTotalRound());
            long lastEndTime = config.getTimeConfigEndTime(timeConfigForward.getTimeId());
            long nowBeginTime = config.getTimeConfigBeginTime(timeConfig.getTimeId());
            if(nowTime < lastEndTime || nowTime > nowBeginTime){
                respMsg.setRet(GameErrorCode.E_PEAK_HOLD_GUESS_TIME);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_GUESS, respMsg);
                MessageHelper.sendPacket(serverId, userId, pbMsg);
                return;
            }
            if(reqMsg.getUnionIdCount() > 3){
                respMsg.setRet(GameErrorCode.E_PEAK_HOLD_GUESS_UNION_COUNT);
                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_GUESS, respMsg);
                MessageHelper.sendPacket(serverId, userId, pbMsg);
                return;
            }
            guessBattle(userId,0,reqMsg.getUnionIdList());
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_GUESS, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    //竞猜信息
    public void guessInfo(long serverId, long userId, PeakStrongholdWarProto.PeakStrongholdGuessListReqMsg reqMsg) {
/*        for(CrossPeakStrongholdUnionData unionData : unionDataMap.values()){
            changeUnionActivityValue(unionData.getUnionId());
        }*/
//        guessChampionResult();
        PeakStrongholdWarProto.PeakStrongholdGuessListRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakStrongholdGuessListRespMsg.newBuilder();
        respMsg.setRet(0);
        long nowTime = System.currentTimeMillis();
        int type = reqMsg.getType();
        PeakStrongholdTimeConfig finalTimeConfig = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), config.getTotalRound());
        if(finalTimeConfig.getTimeId() == type){
            type = 0;
        }
        List<String> unionIdList = guessPassUnionList(type);
        if(type != 0){
            if(!userSelectGuessCountMap.containsKey(type) || userSelectGuessCountMap.get(type).size() == 0){
                guessUnionMake(type);
            }
            for (String unionId : userSelectGuessCountMap.get(type).keySet()) {
                PeakStrongholdWarProto.PeakStrongholdGuessInfoTempMsg.Builder unionTempMsg = PeakStrongholdWarProto.PeakStrongholdGuessInfoTempMsg.newBuilder();
                unionTempMsg.setUnionId(unionId);
                unionTempMsg.setScore(unionDataMap.get(unionId).getScore().intValue());
                unionTempMsg.setUserCount(userSelectGuessCountMap.get(type).get(unionId));
                if(nowTime > config.getTimeConfigEndTime(type)){
                    unionTempMsg.setResult(unionIdList.contains(unionId) ? 1 : 0);
                }else{
                    unionTempMsg.setResult(0);
                }
                CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
                if (unionData != null) {
                    UnionBaseInfo unionBaseInfo = unionData.getUnionBaseInfo();
                    if (unionBaseInfo != null) {
                        unionTempMsg.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
                    } else continue;
                } else continue;
                if (userSelectGuessMap.get(type).containsKey(userId) && userSelectGuessMap.get(type).get(userId).contains(unionId)) {
                    unionTempMsg.setGuess(1);
                } else {
                    unionTempMsg.setGuess(0);
                }
                respMsg.addUnionInfo(unionTempMsg);
            }
        }else{
            if(userFinalsGuessCountMap.size() == 0){
                guessUnionMake(type);
            }
            for (String unionId : userFinalsGuessCountMap.keySet()) {
                PeakStrongholdWarProto.PeakStrongholdGuessInfoTempMsg.Builder unionTempMsg = PeakStrongholdWarProto.PeakStrongholdGuessInfoTempMsg.newBuilder();
                unionTempMsg.setUnionId(unionId);
                unionTempMsg.setScore(unionDataMap.get(unionId).getScore().intValue());
                unionTempMsg.setUserCount(userFinalsGuessCountMap.get(unionId));
                if(nowTime > config.getRoundEndTime(config.getTotalRound())){
                    if (unionIdList.contains(unionId)) {
                        unionTempMsg.setResult(4 - unionIdList.indexOf(unionId));
                    } else {
                        unionTempMsg.setResult(0);
                    }
                }else{
                    unionTempMsg.setResult(0);
                }
                CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
                if (unionData != null) {
                    UnionBaseInfo unionBaseInfo = unionData.getUnionBaseInfo();
                    if (unionBaseInfo != null) {
                        unionTempMsg.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
                    } else continue;
                } else continue;
                if (userFinalsGuessMap.containsKey(userId) && userFinalsGuessMap.get(userId).contains(unionId)) {
                    //0没有猜它，1猜了它(猜8队伍的)，2猜季军，3猜亚军，4猜冠军
                    unionTempMsg.setGuess(4 - userFinalsGuessMap.get(userId).indexOf(unionId));
                } else {
                    unionTempMsg.setGuess(0);
                }
                respMsg.addUnionInfo(unionTempMsg);
            }
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_GUESS_INFO, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    private int getUnionHpAdd(CrossPeakStrongholdUnionData unionData) {
        if (null == unionData) {
            return 0;
        }
        //据点星级
        PeakStrongholdBaseConfig baseConfig = config.getBaseConfigByExp(unionData.getTotalDonateExp());
        if (null == baseConfig) {
            return 0;
        }

        int level = baseConfig.getLevel();
        int hpAdd = getHpAdd(unionData.getUnionId(), level);
        return hpAdd;
    }

    //道具捐献增加经验
    public void itemDonate(String unionId, long serverId, long userId, int exp, int donateId, int num, String rewards) {
        CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
        if (null == unionData) {
            return;
        }
        int expBefore = unionData.getTotalDonateExp();

        lockUnion(unionData.getUnionId());
        try {
            PeakStrongholdUnionMemberInfo memberInfo = unionData.getMemberInfo(userId);
            memberInfo.setDonateExp(exp);
            unionData.setUpdateOption();
            unionData.updateTotalDonateExp();
        } finally {
            unlockUnion(unionData.getUnionId());
        }

        int expAfter = unionData.getTotalDonateExp();

        PeakStrongholdWarProto.CrossPeakHoldItemDonateResp.Builder respMsg = PeakStrongholdWarProto.CrossPeakHoldItemDonateResp.newBuilder();
        respMsg.setActivityId(activityId);
        respMsg.setDonateId(donateId);
        respMsg.setDonateNum(num);
        respMsg.setRewards(rewards);
        respMsg.setBeforeTotalExp(expBefore);
        respMsg.setAfterTotalExp(expAfter);
        respMsg.setRound(this.cacheData.getRound());
        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.S_PEAK_STRONGHOLD_ITEM_DONATE_CROSS_BACK, respMsg));

        sendUnionBaseData(serverId, userId, unionId);
    }

    public void sendUnionBaseData(long serverId, long userId, String unionId) {
        int totalExp = 0;
        CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
        if (null != unionData) {
            totalExp = unionData.getTotalDonateExp();
        }

        PeakStrongholdBaseConfig baseConfig = config.getBaseConfigByExp(totalExp);
        int remainExp = totalExp - baseConfig.getTotalExp();
        PeakStrongholdWarProto.PeakStrongholdUnionBaseSyncMsg.Builder clientMsg = PeakStrongholdWarProto.PeakStrongholdUnionBaseSyncMsg.newBuilder();
        clientMsg.setHoldLevel(baseConfig.getLevel());
        clientMsg.setHoldExp(remainExp);
        if (null != unionData && this.cacheData.getRound() == unionData.getLastRound()) {
            clientMsg.setGroup(unionData.getGroup());
        } else {
            clientMsg.setGroup(0);
        }
        clientMsg.setGroupNum(getNowGroupNum());
        if (this.cacheData.getStageType() == ePeakStrongholdStageType.Registration.getValue()) {
            clientMsg.setOwnUnionRank(getUnionAbilityRank(unionId));
        } else {
            clientMsg.setOwnUnionRank(getUnionScoreRank(unionId));
        }
        clientMsg.setOwnDamageRank(getMemberDamageRank(unionId, userId));

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_UNION_DATA_SYNC, clientMsg));
    }

    public int getNowGroupNum() {
        if (defendUnionsGroupMap.containsKey(this.cacheData.getRound())) {
            return defendUnionsGroupMap.get(this.cacheData.getRound()).size();
        }
        return 0;
    }

    //银两捐献改排行
    public void silverDonate(String unionId, long serverId, long userId, BigInteger silverAmount) {
        CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
        if (null == unionData) {
            return;
        }
        PeakStrongholdUnionMemberInfo memberInfo = unionData.getMemberInfo(userId);
        memberInfo.setSilverAmount(silverAmount);

        lockUnion(unionId);
        try {
            unionData.updateTotalDonateSilver();
            //更新到捐献排行
            addUnionSilverRank(unionData);
            unionSilverRankChange();
        }finally {
            unlockUnion(unionId);
        }

        //不需要单独回包给客户端,客户端单独请求捐献数据
        PeakStrongholdWarProto.PeakStrongholdSilverDonateRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakStrongholdSilverDonateRespMsg.newBuilder();
        respMsg.setRet(0);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_SILVER_DONATE_REQ, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    //商会内银两捐献排行
    public void sendSilverDonateMemberList(String unionId, long serverId, long userId) {
        CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
        if (null == unionData) {
            return;
        }
        List<PeakStrongholdUnionMemberInfo> silverRankList = new ArrayList<>();
        silverRankList.addAll(unionData.getMemberInfoMap().values());
        silverRankList.sort((o1, o2) -> {
            return o2.getSilverAmount().compareTo(o1.getSilverAmount());
        });

        PeakStrongholdWarProto.PeakStrongholdMemberSilverDonateDataRespMsg.Builder clientMsg = PeakStrongholdWarProto.PeakStrongholdMemberSilverDonateDataRespMsg.newBuilder();
        for (PeakStrongholdUnionMemberInfo memberInfo : silverRankList) {
            PeakStrongholdWarProto.PeakSilverDonateDataMsg.Builder memberMsg = PeakStrongholdWarProto.PeakSilverDonateDataMsg.newBuilder();
            UserBaseInfo userBaseInfo = CrossUserMgr.getCrossUserBaseInfo(memberInfo.getUserId()).getUserBaseInfo();
            memberMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            memberMsg.setValue(memberInfo.getSilverAmount().toString());
            clientMsg.addData(memberMsg);
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_MEMBER_SILVER_DONATE, clientMsg));
    }

    //查看自己商会捐献排行数据

    public void sendSilverDonateUnionOwnRank(String unionId, long serverId, long userId) {
        CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
        if (null == unionData) {
            return;
        }
        int rank = getUnionSilverRank(unionId);

        PeakStrongholdWarProto.PeakStrongholdSilverDonateDataRespMsg.Builder clientMsg = PeakStrongholdWarProto.PeakStrongholdSilverDonateDataRespMsg.newBuilder();
        PeakStrongholdWarProto.PeakStrongholdSilverDonateDataMsg.Builder dataBuilder = PeakStrongholdWarProto.PeakStrongholdSilverDonateDataMsg.newBuilder();
        dataBuilder.setRank(rank);
        dataBuilder.setTotalDonate(unionData.getTotalDonateSilver().toString());
        clientMsg.setData(dataBuilder);

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_SILVER_DONATE_DATA, clientMsg));
    }

    //查看商会防守门客参战数据
    public void sendUnionDefendPatronsData(String unionId, long serverId, long userId) {
        CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
        if (null == unionData) {
            return;
        }
        //据点星级
        PeakStrongholdBaseConfig baseConfig = config.getBaseConfigByExp(unionData.getTotalDonateExp());
        if (null == baseConfig) {
            return;
        }

        int level = baseConfig.getLevel();
        int hpAdd = getHpAdd(unionId, level);

        List<PeakStrongholdWarProto.PeakUnionMemberDispatchPatronsTempMsg> defendPatronsMsg = new ArrayList<>();
        //防守血量
        BigInteger totalBlood = BigInteger.ZERO;
        BigInteger baseBlood = BigInteger.ZERO;
        List<PeakStrongholdDefendPatrons> defendPatronsList = unionData.getDefendPatronsList();
        for (PeakStrongholdDefendPatrons defendPatrons : defendPatronsList) {
            BigInteger blood = config.caluPatronsBlood(defendPatrons.getEarnSpeed());

            PeakStrongholdWarProto.PeakUnionMemberDispatchPatronsTempMsg.Builder defendMsg = PeakStrongholdWarProto.PeakUnionMemberDispatchPatronsTempMsg.newBuilder();
            UserBaseInfo userBaseInfo = CrossUserMgr.getCrossUserBaseInfo(defendPatrons.getUserId()).getUserBaseInfo();
            defendMsg.setPlayerData(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            defendMsg.setPatronsId(defendPatrons.getPatronsId());
            defendMsg.setSkinId(defendPatrons.getSkinId());
            defendMsg.setLevel(defendPatrons.getLevel());
            defendMsg.setStageLevel(defendPatrons.getStageLv());
            defendMsg.setEarnSpeed(defendPatrons.getEarnSpeed().toString());
            defendMsg.setBlood(blood.toString());
            defendMsg.setUserId(defendPatrons.getUserId());
            defendPatronsMsg.add(defendMsg.build());

            baseBlood = baseBlood.add(blood);
        }

        totalBlood = baseBlood.add(baseBlood.multiply(BigInteger.valueOf(hpAdd)).divide(BigInteger.valueOf(1000)));

        PeakStrongholdWarProto.UnionPeakStrongholdDefendRespMsg.Builder clientMsg = PeakStrongholdWarProto.UnionPeakStrongholdDefendRespMsg.newBuilder();
        clientMsg.setBattleNum(unionData.getMemberInfoMap().size());
        clientMsg.setStarLv(level);
        clientMsg.setBaseBlood(baseBlood.toString());
        clientMsg.setTotalBlood(totalBlood.toString());
        clientMsg.setHpAdd(hpAdd);
        clientMsg.addAllMemberData(defendPatronsMsg);

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_ELIMINATION_MEMBER_DEFEND_PATRONS, clientMsg));
    }

    //更新积分排行
    private void unionScoreRankChangeSort() {
        unionScoreRankList.sort((o1, o2) -> {
            int compare = o2.getScore().compareTo(o1.getScore());
            if (0 == compare) {
                compare = o2.getTotalGroupScore().compareTo(o1.getTotalGroupScore());
                if (compare == 0) {
                    return o2.getAbility().compareTo(o1.getAbility());
                }
            }
            return compare;
        });
        for (int i = 0; i < unionScoreRankList.size(); i++) {
            int rank = i + 1;
            unionScoreRankList.get(i).setScoreRank(rank);
        }
    }


    //更新捐献排行
    private void unionSilverRankChange() {
        if (!unionSilverRankList.isEmpty()) {
            unionSilverRankList.sort((o1, o2) -> {
                int compare = o2.getTotalDonateSilver().compareTo(o1.getTotalDonateSilver());
                return compare;
            });
        }
        for (int i = 0; i < unionSilverRankList.size(); i++) {
            int rank = i + 1;
            unionSilverRankList.get(i).setSilverRank(rank);
        }
    }

    private void addUnionSilverRank(CrossPeakStrongholdUnionData unionData) {
        if (!unionSilverRankList.contains(unionData)) {
            unionSilverRankList.add(unionData);
        }
    }

    //更新玩家伤害排行
    private void memberDamageRankChange() {
        boolean wrong = false;
        for (PeakStrongholdUnionMemberInfo memberInfo : memberDamageRankList) {
            if (null == memberInfo){
                wrong = true;
                break;
            }
        }
        if (wrong){
            memberDamageRankList.clear();
            for (CrossPeakStrongholdUnionData unionData : unionDataMap.values()) {
                for (PeakStrongholdUnionMemberInfo memberInfo : unionData.getMemberInfoMap().values()) {
                    memberDamageRankList.add(memberInfo);
                }
            }
        }

        if (!memberDamageRankList.isEmpty()) {
            synchronized (memberDamageRankList){
                memberDamageRankList.sort((o1, o2) -> {
                    return o2.getTotalDamage().compareTo(o1.getTotalDamage());
                });
                for (int i = 0; i < memberDamageRankList.size(); i++) {
                    int rank = i + 1;
                    memberDamageRankList.get(i).setDamageRank(rank);
                }
            }
        }
    }

    //查看商会据点列表数据
    public void sendUnionListData(String unionId, long serverId, long userId, int group) {

        List<PeakStrongholdWarProto.PeakEliminateUnionBaseDataMsg> unionMsg = new ArrayList<>();
        if (this.cacheData.getStageType() == ePeakStrongholdStageType.Prepare.getValue()) {
            int rank = 0;
            for (int i = 0; i < unionScoreRankList.size(); i++) {
                CrossPeakStrongholdUnionData unionRankData = unionScoreRankList.get(i);
                CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(this.cacheData.getRound(), unionRankData.getUnionId());
                if (null == defendUnionData || defendUnionData.getGroup() != group) {
                    continue;
                }
                rank++;
                PeakStrongholdWarProto.PeakEliminateUnionBaseDataMsg.Builder unionMsgBuilder = CrossPeakStrongholdPb.buildUnionBaseDataMsg(unionRankData, defendUnionData, config, rank);
                unionMsg.add(unionMsgBuilder.build());
            }
        } else if (this.cacheData.getStageType() == ePeakStrongholdStageType.InBattle.getValue()) {
            List<CrossPeakStrongholdDefendUnionData> groupUnion = getDefendUnionDataList(this.cacheData.getRound(),group);
            if (null != groupUnion) {
                for (int i = 0; i < groupUnion.size(); i++) {
                    CrossPeakStrongholdDefendUnionData defendUnionData = groupUnion.get(i);
                    if(defendUnionData.getGroupRank() == 0){
                        updateRoundDamageRank(group);
                        updateNowScoreRank();
                    }
                    CrossPeakStrongholdUnionData unionRankData = getUnionData(defendUnionData.getUnionId());
                    PeakStrongholdWarProto.PeakEliminateUnionBaseDataMsg.Builder unionMsgBuilder = CrossPeakStrongholdPb.buildUnionBaseDataMsg(unionRankData, defendUnionData, config, 0);
                    unionMsg.add(unionMsgBuilder.build());
                }
            }
        }


        PeakStrongholdWarProto.GetPeakEliminateUnionListRespMsg.Builder clientMsg = PeakStrongholdWarProto.GetPeakEliminateUnionListRespMsg.newBuilder();
        clientMsg.addAllUnionData(unionMsg);
        CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
        if (null != unionData) {
            clientMsg.setRandSeed(unionData.getRandSeed());
        } else {
            clientMsg.setRandSeed(0);
        }

        clientMsg.setStageType(this.cacheData.getStageType());
        if(groupFirstMemberMap.containsKey(this.cacheData.getRound())){
            PeakStrongholdUnionMemberInfo firstMember = groupFirstMemberMap.get(this.cacheData.getRound()).get(group);
            if (null != firstMember) {
                UserBaseInfo firstUserInfo = CrossUserMgr.getUserBaseInfo(firstMember.getUserId());
                if (null != firstUserInfo) {
                    clientMsg.setFirstRankUser(PlayerBasePb.parsePlayerBaseTempMsg(firstUserInfo));
                }
            }
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_ELIMINATION_UNION_DATA, clientMsg));
    }

    public void sendUnionInsideData(String ownUnionId, String targetUnionId, long serverId, long userId) {
        if (Objects.equals(ownUnionId, targetUnionId)){
            return;
        }
        CrossPeakStrongholdUnionData unionData = getUnionData(ownUnionId);
        if (null == unionData) {
            return;
        }
        CrossPeakStrongholdUnionData targetUnionData = getUnionData(targetUnionId);
        if (null == targetUnionData) {
            return;
        }
        if(unionData.getGroup() != targetUnionData.getGroup()) {
            return;
        }
        CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(this.cacheData.getRound(), targetUnionId);

        PeakStrongholdWarProto.ChoosePeakChallengeUnionRespMsg.Builder clientMsg = PeakStrongholdWarProto.ChoosePeakChallengeUnionRespMsg.newBuilder();
        clientMsg.setRet(0);

        PeakStrongholdWarProto.PeakEliminateUnionBaseDataMsg.Builder unionMsgBuilder = CrossPeakStrongholdPb.buildUnionBaseDataMsg(targetUnionData, defendUnionData, config, 0);
        clientMsg.setUnionInfo(unionMsgBuilder);

        PeakStrongholdDefendPatrons defendPatrons = defendUnionData.getDefendPatrons();
        if (null != defendPatrons) {
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(defendPatrons.getUserId());
            if (null != userBaseInfo) {
                PeakStrongholdWarProto.PeakEliminateChallengePatronsDataMsg.Builder defendPatronMsg = CrossPeakStrongholdPb.buildPatronsDataMsg(userBaseInfo, defendPatrons);
                clientMsg.setPatrons(defendPatronMsg);
            }
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_ELIMINATION_ENTER_UNION, clientMsg));

    }

    //进攻据点
    public AttackUnionResult attackDefendUnion(String ownUnionId, String targetUnionId, long userId, BigInteger damage) {
        if (!isStageTypeNormal()) {
            return new AttackUnionResult(GameErrorCode.E_PEAK_HOLD_DEFEND_DATA_UPDATING);
        }
        lockUnion(targetUnionId);
        try {
            if (this.cacheData.getStageType() == ePeakStrongholdStageType.HoldDefendCreate.getValue()) {
                return new AttackUnionResult(GameErrorCode.E_PEAK_HOLD_DEFEND_DATA_UPDATING);
            }
            if (this.cacheData.getStageType() != ePeakStrongholdStageType.InBattle.getValue()) {
                //不在战斗阶段
                return new AttackUnionResult(GameErrorCode.E_PEAK_HOLD_ELIMINATE_NOT_BEGIN);
            }
            if (Objects.equals(ownUnionId, targetUnionId)) {
                //别打自己
                return new AttackUnionResult(GameErrorCode.E_STRONGHOLD_ATTACK_SELF);
            }
            CrossPeakStrongholdUnionData attackUnion = getUnionData(ownUnionId);
            if (attackUnion == null || attackUnion.getLastRound() != config.getRound()) {
                return new AttackUnionResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_BEEN_BEATED);
            }
            PeakStrongholdUnionMemberInfo memberInfo = attackUnion.getMemberInfo(userId);
            if (null == memberInfo) {
                return new AttackUnionResult(GameErrorCode.E_PEAK_HOLD_NOT_IN_DEFEND_MEMBER);
            }

            CrossPeakStrongholdUnionData enemyUnion = getUnionData(targetUnionId);
            if (attackUnion == null || attackUnion.getLastRound() != config.getRound()) {
                return new AttackUnionResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_ENEMY_BEEN_BEATED);
            }
            if (attackUnion.getGroup() != enemyUnion.getGroup()) {
                return new AttackUnionResult(GameErrorCode.E_PEAK_HOLD_NOT_IN_SAME_GROUP);
            }

            CrossPeakStrongholdDefendUnionData attackDefendUnion = getDefendUnionData(this.cacheData.getRound(), ownUnionId);
            if (attackDefendUnion == null) {
                return new AttackUnionResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_BEEN_BEATED);
            }

            CrossPeakStrongholdDefendUnionData enemyDefendUnion = getDefendUnionData(this.cacheData.getRound(), targetUnionId);
            if (enemyDefendUnion == null) {
                return new AttackUnionResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_ENEMY_BEEN_BEATED);
            }

            PeakStrongholdTimeConfig curBattleTimeConfig = config.getCurBattleTimeConfig();
            if (curBattleTimeConfig == null || config.getRoundByTimeId(curBattleTimeConfig.getTimeId())!=attackDefendUnion.getRound()) {
                return new AttackUnionResult(GameErrorCode.E_PEAK_HOLD_ELIMINATE_NOT_BEGIN);
            }

            if (enemyDefendUnion.getCurBlood().compareTo(BigInteger.ZERO) <= 0) {
                //对方联盟血量为0
                return new AttackUnionResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_ENEMY_BEEN_BEATED);
            }
            PeakStrongholdDefendPatrons defendPatrons = enemyDefendUnion.getCurDefendPatrons();
            if (defendPatrons == null) {
                return new AttackUnionResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_ENEMY_BEEN_BEATED);
            }

            AttackResult result = realAttack(memberInfo, attackUnion, attackDefendUnion, enemyUnion, enemyDefendUnion, damage);
            BigInteger memberDamage = memberInfo.getTotalDamage();
            defendPatrons = enemyDefendUnion.getCurDefendPatrons();
            return new AttackUnionResult(defendPatrons, result.getKillNum(), enemyDefendUnion, result.getTotalDamage().toString(), memberDamage.toString());
        } finally {
            unlockUnion(targetUnionId);
        }
    }

    private AttackResult realAttack(PeakStrongholdUnionMemberInfo memberInfo,
                                    CrossPeakStrongholdUnionData attackUnion, CrossPeakStrongholdDefendUnionData attackDefendUnion,
                                    CrossPeakStrongholdUnionData enemyUnion, CrossPeakStrongholdDefendUnionData enemyDefendUnion,
                                    BigInteger damage) {
        int killNum = 0;
        int attackUnionNum = 0;
        boolean isAttack = false;
        PeakStrongholdDefendPatrons defendPatrons = null;

        if (enemyDefendUnion.getCurBlood().compareTo(BigInteger.ZERO) > 0) {
            isAttack = true;
            defendPatrons = enemyDefendUnion.getCurDefendPatrons();
            if (damage.compareTo(defendPatrons.getCurBlood()) >= 0) {
                damage = new BigInteger(defendPatrons.getCurBlood().toString());
                killNum++;
            }
            enemyUnion.setLastFightTime(System.currentTimeMillis());
            defendPatrons.setCurBlood(defendPatrons.getCurBlood().subtract(damage));
            //累计玩家个人伤害
            memberInfo.setTotalDamage(memberInfo.getTotalDamage().add(damage));
            memberInfo.setRoundDamage(memberInfo.getRoundDamage().add(damage));
            updateGroupFirstDamageMember(this.cacheData.getRound(),attackDefendUnion.getGroup(), memberInfo);

            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberInfo.getUserId());
            if(userBaseInfo != null){
                CrossConditionSyncData data = new CrossConditionSyncData();
                data.setServerId(userBaseInfo.getServerId());
                data.setUserId(memberInfo.getUserId());
                data.setType(eGamePlayerEventType.PeakStrongHoldUserDamageRank.getValue());
                data.setValue(memberInfo.getTotalDamage());
                data.setParam("");
                addNeedSyncCondition(data);
            }

            //更新个人伤害排行
            //memberDamageRankChange();
            damageRankChangeMark = true;

            if (attackDefendUnion.getCurBlood().compareTo(BigInteger.ZERO) > 0) {
                // 商会还存在 才计算总伤害
                attackUnion.addTotalDamage(damage);
                attackDefendUnion.addTotalDamage(damage);
            }
            //每轮淘汰赛商会积分计算=商会总伤害*（1+当前回合商会据点血量百分比*2）/3
            BigInteger attackSocre = config.calcDamageToScore(attackDefendUnion.getTotalDamage(), attackDefendUnion.getCurBlood(), attackDefendUnion.getTotalBlood());
            attackDefendUnion.setGroupScore(attackSocre);
            BigInteger enemySocre = config.calcDamageToScore(enemyDefendUnion.getTotalDamage(), enemyDefendUnion.getCurBlood(), enemyDefendUnion.getTotalBlood());
            enemyDefendUnion.setGroupScore(enemySocre);
            //更新商会伤害排行
            updateRoundDamageRank(attackUnion.getGroup());

            // 生成伤害记录
            BigInteger attackDamage = attackDefendUnion.getAttackDamage(enemyUnion.getUnionId(), memberInfo.getUserId());
            BigInteger totalAttackDamage = attackDamage.add(damage);
            //打了谁
            attackDefendUnion.addAttackDamage(enemyUnion.getUnionId(), memberInfo.getUserId(), totalAttackDamage);

            BigInteger defendDamage = enemyDefendUnion.getDefendDamage(attackUnion.getUnionId(), memberInfo.getUserId());
            BigInteger totalDefendDamage = defendDamage.add(damage);
            //被谁打
            enemyDefendUnion.addDefendDamage(attackUnion.getUnionId(), memberInfo.getUserId(), totalDefendDamage);
        }
        if (isAttack) {
            attackUnionNum += 1;
        }
        AttackResult result = new AttackResult(killNum, damage, attackUnionNum);
        result.setPeakHolddefendPatrons(defendPatrons);
        noticeMyUnionFailed(enemyUnion, enemyDefendUnion);
        noticeMyUnionFailed(attackUnion, attackDefendUnion);

        attackUnion.setUpdateOption();
        attackDefendUnion.setUpdateOption();
        enemyUnion.setUpdateOption();
        enemyDefendUnion.setUpdateOption();

        return result;

    }

    private void noticeMyUnionFailed(CrossPeakStrongholdUnionData unionData, CrossPeakStrongholdDefendUnionData defendUnion) {
        if (defendUnion.getCurBlood().compareTo(BigInteger.ZERO) <= 0) {
            List<Long> serverIds = new ArrayList<>();
            StrongholdWarProto.CrossStrongholdEliminateUnionStatusRespMsg.Builder resp = StrongholdWarProto.CrossStrongholdEliminateUnionStatusRespMsg.newBuilder();
            resp.setActivityId(activityId);
            resp.setUnionId(defendUnion.getUnionId());
            resp.setExist(false);
            resp.setUserId(0);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(GameProtocol.S_CROSS_STRONGHOLD_ELIMINATE_UNION_STATUS, resp);
            for (PeakStrongholdUnionMemberInfo memberInfo : unionData.getMemberInfoMap().values()) {
                long serverId = CrossUserMgr.getServerIdByUserId(memberInfo.getUserId());
                if (!serverIds.contains(serverId)) {
                    serverIds.add(serverId);
                    MessageHelper.sendPacket(serverId, 0, pbMsg);
                }
            }
        }
    }

    public void sendHoldDamageReport(long serverId, long userId, String unionId, int type) {
        CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(this.cacheData.getRound(), unionId);
        if (null == defendUnionData) {
            return;
        }

        Map<String, Map<Long, BigInteger>> unionDamage = new ConcurrentHashMap<>();
        if (type == 1) {
            //打了谁
            unionDamage = defendUnionData.getAttackUnionMap();
        } else {
            //被谁打
            unionDamage = defendUnionData.getDefendUnionMap();
        }

        PeakStrongholdWarProto.GetPeakEliminateUnionReportRespMsg.Builder clientMsg = PeakStrongholdWarProto.GetPeakEliminateUnionReportRespMsg.newBuilder();
        clientMsg.setType(type);

        for (Map.Entry<String, Map<Long, BigInteger>> unionDamageMap : unionDamage.entrySet()) {
            String enemyUnionId = unionDamageMap.getKey();
            CrossPeakStrongholdUnionData enemyUnionData = getUnionData(enemyUnionId);
            if (null == enemyUnionData) {
                continue;
            }
            CrossPeakStrongholdDefendUnionData enemyDefendUnionData = getDefendUnionData(this.cacheData.getRound(), enemyUnionId);
            if (null == enemyDefendUnionData) {
                continue;
            }
            BigInteger totalDamage = BigInteger.ZERO;
            for (BigInteger damage : unionDamageMap.getValue().values()) {
                totalDamage = totalDamage.add(damage);
            }
            PeakStrongholdWarProto.PeakStrongholdEliminateUnionReportDataMsg.Builder unionDamageMsg = PeakStrongholdWarProto.PeakStrongholdEliminateUnionReportDataMsg.newBuilder();
            unionDamageMsg.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(enemyUnionData.getUnionBaseInfo()));
            BigInteger totalBlood = BigInteger.ZERO;
            if (type == 1) {
                totalBlood = enemyDefendUnionData.getTotalBlood();
            } else {
                totalBlood = defendUnionData.getTotalBlood();
            }
            int damageRate = totalDamage.multiply(BigInteger.valueOf(10000)).divide(totalBlood).intValue();
            if (damageRate == 0) {
                damageRate = 1;
            } else if (damageRate >= 10000) {
                damageRate = 10000;
            }
            unionDamageMsg.setDamageRate(damageRate);
            clientMsg.addReport(unionDamageMsg);
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_ELIMINATION_REPORT, clientMsg));
    }

    public void sendHoldMemberDamageReport(long serverId, long userId, String unionId, String enemyUnionId, int type) {
        CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(this.cacheData.getRound(), unionId);
        if (null == defendUnionData) {
            return;
        }

        PeakStrongholdWarProto.GetPeakEliminateReportDetailRespMsg.Builder clientMsg = PeakStrongholdWarProto.GetPeakEliminateReportDetailRespMsg.newBuilder();
        clientMsg.setType(type);

        if (StringUtils.isNullOrEmpty(enemyUnionId)){//发空的过来就发成员本回合总伤害
            CrossPeakStrongholdUnionData unionData = getUnionData(defendUnionData.getUnionId());
            for (PeakStrongholdUnionMemberInfo memberInfo : unionData.getMemberInfoMap().values()) {
                long memberUserId = memberInfo.getUserId();
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberUserId);
                if (null == userBaseInfo) {
                    continue;
                }
                PeakStrongholdWarProto.PeakStrongholdEliminateReportDetailMsg.Builder memberMsg = PeakStrongholdWarProto.PeakStrongholdEliminateReportDetailMsg.newBuilder();
                memberMsg.setNickName(userBaseInfo.getNickName());
                memberMsg.setDamage(memberInfo.getRoundDamage().toString());
                clientMsg.addReport(memberMsg);
            }
        } else {
            Map<Long, BigInteger> memberDamageMap = new HashMap<>();
            if (type == 1) {
                //打了谁
                memberDamageMap = defendUnionData.getAttackUnionMap().get(enemyUnionId);
            } else {
                //被谁打
                memberDamageMap = defendUnionData.getDefendUnionMap().get(enemyUnionId);
            }

            if (null != memberDamageMap) {
                for (Map.Entry<Long, BigInteger> memberDamage : memberDamageMap.entrySet()) {
                    long memberUserId = memberDamage.getKey();
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberUserId);
                    if (null == userBaseInfo) {
                        continue;
                    }
                    PeakStrongholdWarProto.PeakStrongholdEliminateReportDetailMsg.Builder memberMsg = PeakStrongholdWarProto.PeakStrongholdEliminateReportDetailMsg.newBuilder();
                    memberMsg.setNickName(userBaseInfo.getNickName());
                    memberMsg.setDamage(memberDamage.getValue().toString());
                    clientMsg.addReport(memberMsg);
                }
            }
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_ELIMINATION_MEMBER_DAMAGE, clientMsg));
    }

    /**
     * 设置最后一次使用财神助力的攻击时间
     * @param userId
     */
    public void setLastMammonHelpTime(long userId){
        synchronized (mammonHelpLastTimeMap){
            mammonHelpLastTimeMap.put(userId,System.currentTimeMillis());
        }
    }

    /**
     * 检测玩家财神助力是否过于频繁
     * @param userId
     * @return
     */

    public boolean checkMammonHelpTooOften(long userId){
        synchronized (mammonHelpLastTimeMap){
            if (mammonHelpLastTimeMap.containsKey(userId)){
                long lastTime = mammonHelpLastTimeMap.get(userId);
                if (System.currentTimeMillis() - lastTime < config.getMammonHelpItemCd()){
                    return true;
                }
            }
        }
        return false;
    }


    //财神助力
    public MammonHelpResult mammonHelp(long userId, String unionId, int mammonType, String targetUnionId, BigInteger totalDamage, int randomTimes) {

        if (!isStageTypeNormal()) {
            return new MammonHelpResult(GameErrorCode.E_PEAK_HOLD_DEFEND_DATA_UPDATING);
        }

        if (this.cacheData.getStageType() != ePeakStrongholdStageType.InBattle.getValue()) {
            //不在战斗阶段
            return new MammonHelpResult(GameErrorCode.E_PEAK_HOLD_ELIMINATE_NOT_BEGIN);
        }
        String myUnionId = unionId;
        CrossPeakStrongholdUnionData attackUnion = getUnionData(myUnionId);
        if (null == attackUnion) {
            return new MammonHelpResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_BEEN_BEATED);
        }
        PeakStrongholdUnionMemberInfo memberInfo = attackUnion.getMemberInfo(userId);
        if (null == memberInfo) {
            return new MammonHelpResult(GameErrorCode.E_PEAK_HOLD_NOT_IN_DEFEND_MEMBER);
        }
        CrossPeakStrongholdDefendUnionData attackDefendUnion = getDefendUnionData(this.cacheData.getRound(), myUnionId);
        if (null == attackDefendUnion) {
            return new MammonHelpResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_BEEN_BEATED);
        }

        PeakStrongholdTimeConfig curBattleTimeConfig = config.getCurBattleTimeConfig();
        if (curBattleTimeConfig == null || config.getRoundByTimeId(curBattleTimeConfig.getTimeId())!=attackDefendUnion.getRound()) {
            return new MammonHelpResult(GameErrorCode.E_PEAK_HOLD_ELIMINATE_NOT_BEGIN);
        }
        boolean tooOften = checkMammonHelpTooOften(userId);
        //财神助力过于频繁
        if (tooOften){
            return new MammonHelpResult(GameErrorCode.E_PEAK_HOLD_MAMMON_HELP_TOO_OFTEN);
        }

        int group = attackDefendUnion.getGroup();
        if (mammonType == 1) {
            return attackAppointUnion(attackUnion, attackDefendUnion, memberInfo, targetUnionId, totalDamage);
        } else {
            int totalKillNum = 0;
            BigInteger resultDamage = BigInteger.ZERO;
            int totalAttackNum = 0;

            List<String> attackUnionList = new ArrayList<>();
            Map<String, BigInteger> unionDamageMap = new HashMap<>();
            Map<String, Integer> unionRemainBloodMap = new HashMap<>();
            //随机找N个联盟
            Set<String> attackUnionSet = new HashSet<>();
            List<CrossPeakStrongholdDefendUnionData> unionList = findAllOtherUnion(myUnionId, group);
            if (unionList.size() == 0) {
                return new MammonHelpResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_NO_ANY_UNION);
            }

            synchronized (defendUnionsGroupMap) {
                for (int i = 0; i < randomTimes; i++) {
                    unionList = findAllOtherUnion(myUnionId, group);
                    if (unionList.isEmpty()) {
                        break;
                    }
                    int index = randomHelper.next(0, unionList.size());
                    CrossPeakStrongholdDefendUnionData enemyDefendunion = unionList.get(index);
                    CrossPeakStrongholdUnionData enemyUnion = getUnionData(enemyDefendunion.getUnionId());
                    attackUnionSet.add(enemyDefendunion.getUnionId());
                    AttackResult result = realAttack(memberInfo, attackUnion, attackDefendUnion, enemyUnion, enemyDefendunion, totalDamage);
                    resultDamage = resultDamage.add(result.getTotalDamage());
                    totalKillNum += result.getKillNum();
                    attackUnionList.add(enemyDefendunion.getUnionId());
                    if (unionDamageMap.containsKey(enemyDefendunion.getUnionId())) {
                        unionDamageMap.put(enemyDefendunion.getUnionId(), unionDamageMap.get(enemyDefendunion.getUnionId()).add(result.getTotalDamage()));
                    } else {
                        unionDamageMap.put(enemyDefendunion.getUnionId(), new BigInteger(result.getTotalDamage().toString()));
                    }
                    int remainBlood = CrossStrongholdActivityMgr.calcEliminateCurBlood(enemyDefendunion.getCurBlood(), enemyDefendunion.getTotalBlood());
                    if (unionRemainBloodMap.containsKey(enemyDefendunion.getUnionId())) {
                        if (remainBlood < unionRemainBloodMap.get(enemyDefendunion.getUnionId())) {
                            remainBlood = unionRemainBloodMap.get(enemyDefendunion.getUnionId());
                        }
                    }
                    unionRemainBloodMap.put(enemyDefendunion.getUnionId(), remainBlood);
                }
            }
            totalAttackNum = attackUnionSet.size();
            MammonHelpResult result = new MammonHelpResult(totalKillNum, totalAttackNum, resultDamage);
            result.setUnionDamageMapEx(unionDamageMap);
            result.setMemberTotalDamage(memberInfo.getTotalDamage());
            result.setUnionRemainBloodMap(unionRemainBloodMap);
            setLastMammonHelpTime(userId);
            return result;
        }
    }

    /**
     * 攻击指定联盟
     *
     * @return
     */
    private MammonHelpResult attackAppointUnion(CrossPeakStrongholdUnionData attackUnion, CrossPeakStrongholdDefendUnionData attackDefendUnion, PeakStrongholdUnionMemberInfo memberInfo, String targetUnionId, BigInteger totalDamage) {

        if (StringUtils.isNullOrEmpty(targetUnionId)) {
            return new MammonHelpResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_ENEMY_BEEN_BEATED);
        }

        lockUnion(targetUnionId);
        try {
            String unionName = "";
            CrossPeakStrongholdDefendUnionData enemyDefendUnion = getDefendUnionData(this.cacheData.getRound(), targetUnionId);
            if (enemyDefendUnion == null || enemyDefendUnion.getCurBlood().compareTo(BigInteger.ZERO) <= 0) {
                return new MammonHelpResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_ENEMY_BEEN_BEATED);
            }
            if (attackUnion.getUnionId().equals(targetUnionId)) {
                return new MammonHelpResult(GameErrorCode.E_STRONGHOLD_ATTACK_SELF);
            }
            CrossPeakStrongholdUnionData enemyUnionData = getUnionData(enemyDefendUnion.getUnionId());
            if (null == enemyUnionData) {
                return new MammonHelpResult(GameErrorCode.E_STRONGHOLD_ELIMINATE_ENEMY_BEEN_BEATED);
            }
            if (enemyDefendUnion.getGroup() != attackDefendUnion.getGroup()) {
                return new MammonHelpResult(GameErrorCode.E_PEAK_HOLD_NOT_IN_SAME_GROUP);
            }
            unionName = enemyUnionData.getUnionBaseInfo().getUnionName();

            int totalKillNum = 0;
            BigInteger resultDamage = BigInteger.ZERO;
            int totalAttackNum = 0;

            Map<String, BigInteger> unionDamageMap = new HashMap<>();
            Map<String, Integer> unionRemainBloodMap = new HashMap<>();
            BigInteger attackDamage = totalDamage;
            while (attackDamage.compareTo(BigInteger.ZERO) > 0 && !enemyDefendUnion.isBloodEmpty()) {
                // 当伤害值还有，且联盟未被击败，继续打
                AttackResult result = realAttack(memberInfo, attackUnion, attackDefendUnion, enemyUnionData, enemyDefendUnion, attackDamage);
                BigInteger realDamage = result.getTotalDamage();
                attackDamage = attackDamage.subtract(realDamage);
                if (unionDamageMap.containsKey(enemyDefendUnion.getUnionId())) {
                    unionDamageMap.put(enemyDefendUnion.getUnionId(), unionDamageMap.get(enemyDefendUnion.getUnionId()).add(realDamage));
                } else {
                    unionDamageMap.put(enemyDefendUnion.getUnionId(), new BigInteger(realDamage.toString()));
                }
                int remainBlood = CrossStrongholdActivityMgr.calcEliminateCurBlood(enemyDefendUnion.getCurBlood(), enemyDefendUnion.getTotalBlood());
                if (unionRemainBloodMap.containsKey(enemyDefendUnion.getUnionId())) {
                    if (remainBlood > unionRemainBloodMap.get(enemyDefendUnion.getUnionId())) {
                        remainBlood = unionRemainBloodMap.get(enemyDefendUnion.getUnionId());
                    }
                }
                unionRemainBloodMap.put(enemyDefendUnion.getUnionId(), remainBlood);
                totalKillNum += result.getKillNum();
                resultDamage = resultDamage.add(realDamage);
            }
            totalAttackNum += 1;
            MammonHelpResult result = new MammonHelpResult(totalKillNum, totalAttackNum, resultDamage);
            result.setUnionDamageMapEx(unionDamageMap);
            result.setUnionName(unionName);
            result.setMemberTotalDamage(memberInfo.getTotalDamage());
            result.setUnionRemainBloodMap(unionRemainBloodMap);
            setLastMammonHelpTime(memberInfo.getUserId());
            return result;
        } finally {
            unlockUnion(targetUnionId);
        }
    }

    private List<CrossPeakStrongholdDefendUnionData> findAllOtherUnion(String myUnionId, int group) {
        List<CrossPeakStrongholdDefendUnionData> tempUnionList = new ArrayList<>();
        for (CrossPeakStrongholdDefendUnionData union : getDefendUnionDataList(this.cacheData.getRound(), group)) {
            if (!union.getUnionId().equals(myUnionId) && union.getCurBlood().compareTo(BigInteger.ZERO) > 0) {
                //不是本方 且还有血量
                tempUnionList.add(union);
            }
        }

        return tempUnionList;
    }

    //更新门客赚钱排行
    @Deprecated
    private void updateUnionAbilityRank(String unionId, UnionBaseInfo unionBaseInfo, BigInteger ability) {
        boolean isChange = false;
        synchronized (abilityRankList) {
            if (abilityRankMap.containsKey(unionId)) {
                CrossUnionAbilityRankData rankData = abilityRankMap.get(unionId);
                if (rankData.getAbility().compareTo(ability) != 0) {
                    rankData.setAbility(ability);
                    rankData.setUpdateOption();
                    isChange = true;
                }
            } else {
                PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.Registration.getValue(), 0);
                int rankNumLimit = Integer.parseInt(timeConfig.getParam()) + 20;
                CrossUnionAbilityRankData rankData = null;

                if (abilityRankMap.size() < rankNumLimit) {
                    rankData = new CrossUnionAbilityRankData();
                    rankData.setInsertOption();
                    rankData.setActivityId(activityId);
                    rankData.setRankId(abilityRankMap.size() + 1);
                    abilityRankList.add(rankData);
                } else {
                    rankData = abilityRankList.get(abilityRankList.size() - 1);
                    if (rankData.getAbility().compareTo(ability) >= 0) {
                        //值没有超过最后一名,无变化
                        return;
                    }
                }
                String oldUnionId = rankData.getUnionId();
                if (!StringUtils.isNullOrEmpty(oldUnionId) && !oldUnionId.equals(unionId)) {
                    abilityRankMap.remove(oldUnionId);
                }
                rankData.setAbility(ability);
                rankData.setUnionId(unionId);
                rankData.setUnionBaseInfo(unionBaseInfo);
                rankData.setUpdateOption();
                abilityRankMap.put(unionId, rankData);

                isChange = true;
            }
        }

        if (isChange) {
            unionAbilityRankChange();
            //abilityRankChangeMark = true;
        }
    }

    @Deprecated
    private CrossUnionAbilityRankData getUnionAbilityRankData(String unionId) {
        return abilityRankMap.get(unionId);
    }

    @Deprecated
    private void deleteUnionAbilityRank(String unionId) {
        if (!abilityRankMap.containsKey(unionId)) {
            return;
        }
        synchronized (abilityRankList) {
            CrossUnionAbilityRankData rankData = abilityRankMap.get(unionId);
            rankData.setAbility(BigInteger.ZERO);
        }

        unionAbilityRankChange();
        //abilityRankChangeMark = true;
    }

    @Deprecated
    private void unionAbilityRankChange() {
        if (abilityRankList.isEmpty()) {
            return;
        }
        synchronized (abilityRankList) {
            abilityRankList.sort((o1, o2) -> {
                return o2.getAbility().compareTo(o1.getAbility());
            });

            if (abilityRankList.size() != abilityRankMap.size()) {
                abilityRankMap.clear();
            }

            for (int i = 0; i < abilityRankList.size(); i++) {
                int rank = i + 1;
                abilityRankList.get(i).setRank(rank);
                abilityRankMap.put(abilityRankList.get(i).getUnionId(), abilityRankList.get(i));
            }
        }

    }

    @Deprecated
    private List<CrossUnionAbilityRankData> getAbilityRankList() {
        List<CrossUnionAbilityRankData> tempList = new ArrayList<>();
        if (abilityRankList.isEmpty()) {
            return tempList;
        }
        synchronized (abilityRankList) {
            tempList.addAll(abilityRankList);
        }
        return tempList;
    }

    //发送门客赚钱排行
//    public void sendUnionAbilityRank(long serverId, long userId, String unionId) {
//        PeakStrongholdWarProto.PeakStrongholdUnionAbilityRankRespMsg.Builder clientMsg = PeakStrongholdWarProto.PeakStrongholdUnionAbilityRankRespMsg.newBuilder();
//
//        int ownRank = 0;
//        int rank = 1;
//        String myValue = "0";
//        List<CrossUnionAbilityRankData> rankList = getAbilityRankList();
//        for (int i = 0; i < rankList.size(); i++) {
//            CrossUnionAbilityRankData rankData = rankList.get(i);
//            if (rankData.getAbility().compareTo(BigInteger.ZERO) == 0) {
//                continue;
//            }
//            if (rankData.getUnionId().equals(unionId)) {
//                ownRank = rank;
//                myValue = rankData.getAbility().toString();
//            }
//
//            PeakStrongholdWarProto.UnionAbilityRankTemp.Builder rankMsg = PeakStrongholdWarProto.UnionAbilityRankTemp.newBuilder();
//            rankMsg.setRank(rank++);
//            rankMsg.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(rankData.getUnionBaseInfo()));
//            rankMsg.setAbility(rankData.getAbility().toString());
//            rankMsg.setUnionId(rankData.getUnionId());
//            clientMsg.addRankData(rankMsg);
//        }
//
//        clientMsg.setOwnRank(ownRank);
//        if (ownRank == 0) {
//            CrossUnionAbilityCacheData unionAbilityCacheData = getUnionAbilityCacheData(unionId);
//            if (null != unionAbilityCacheData) {
//                BigInteger total = BigInteger.ZERO;
//                for (BigInteger ability : unionAbilityCacheData.getUserAbility().values()) {
//                    total = total.add(ability);
//                }
//                myValue = total.toString();
//            }
//        }
//        clientMsg.setValue(myValue);
//
//        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_UNION_ABILITY_RANK, clientMsg));
//
//    }

    public void sendUnionSilverRank(long serverId, long userId, String unionId) {
        PeakStrongholdWarProto.PeakStrongholdUnionSilverRankRespMsg.Builder clientMsg = PeakStrongholdWarProto.PeakStrongholdUnionSilverRankRespMsg.newBuilder();

        int ownRank = -1;
        int rank = 1;
        for (CrossPeakStrongholdUnionData rankData : unionSilverRankList) {
            BigInteger silver = rankData.getTotalDonateSilver();
            if (silver.compareTo(BigInteger.ZERO) == 0) {
                continue;
            }
            if (rankData.getUnionId().equals(unionId)) {
                ownRank = rank;
            }

            PeakStrongholdWarProto.UnionSilverRankTemp.Builder rankMsg = PeakStrongholdWarProto.UnionSilverRankTemp.newBuilder();
            rankMsg.setRank(rank++);
            rankMsg.setUnionInfo(UnionBasePb.parseUnionBaseTempMsg(rankData.getUnionBaseInfo()));
            rankMsg.setSilver(silver.toString());
            rankMsg.setUnionId(rankData.getUnionId());
            clientMsg.addRankData(rankMsg);
        }
        clientMsg.setOwnRank(ownRank);

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_UNION_SILVER_RANK, clientMsg));

    }

    private Lock getUnionLock(String unionId) {
        Lock lock = unionLock.get(unionId);
        if (null == lock) {
            synchronized (unionLock) {
                lock = unionLock.get(unionId);
                if (null == lock) {
                    lock = new ReentrantLock();
                    unionLock.put(unionId, lock);
                }
            }
        }
        return lock;
    }

    private Lock getGroupLock(int group) {
        Lock lock = groupLock.get(group);
        if (null == lock) {
            synchronized (groupLock) {
                lock = groupLock.get(group);
                if (null == lock) {
                    lock = new ReentrantLock();
                    groupLock.put(group, lock);
                }
            }
        }
        return lock;
    }

    private void lockUnion(String unionId) {
        Lock lock = getUnionLock(unionId);
        lock.lock();
    }

    private void unlockUnion(String unionId) {
        Lock lock = unionLock.get(unionId);
        if (null != lock) {
            lock.unlock();
        }
    }

    private void lockGroup(int group) {
        Lock lock = getGroupLock(group);
        lock.lock();

    }

    private void unlockGroup(int group) {
        Lock lock = groupLock.get(group);
        if (null != lock) {
            lock.unlock();
        }
    }

    private void lockUnions(List<String> unionIds) {
        for (String unionId : unionIds) {
            Lock lock = getUnionLock(unionId);
            lock.lock();
        }
    }

    private void unlockUnions(List<String> unionIds) {
        for (String unionId : unionIds) {
            Lock lock = unionLock.get(unionId);
            if (null != lock) {
                lock.unlock();
            }
        }
    }

    public void timerRankSort() {
        if (damageRankChangeMark) {
            damageRankChangeMark = false;
            memberDamageRankChange();
            updateNowScoreRank();
        }
//        if (abilityRankChangeMark) {
//            abilityRankChangeMark = false;
//            unionAbilityRankChange();
//        }
    }

    public void updateRoundDamageRank(int group) {
        lockGroup(group);
        try {
            List<CrossPeakStrongholdDefendUnionData> groupUnion = unionRoundDamageRank.get(group);
            if (null != groupUnion) {
                groupUnion.sort((o1, o2) -> {
                    int scoreCompare = o2.getGroupScore().compareTo(o1.getGroupScore());
                    if (scoreCompare == 0) {
                        CrossPeakStrongholdUnionData unionData1 = getUnionData(o1.getUnionId());
                        CrossPeakStrongholdUnionData unionData2 = getUnionData(o2.getUnionId());
                        return unionData2.getAbility().compareTo(unionData1.getAbility());
                    }
                    return scoreCompare;
                });
                for (int i = 0; i < groupUnion.size(); i++) {
                    int rank = i + 1;
                    groupUnion.get(i).setGroupRank(rank);
                }
            }
        }finally {
            unlockGroup(group);
        }
    }

    public void initRoundDamageRank() {
        for (List<CrossPeakStrongholdDefendUnionData> groupUnion : unionRoundDamageRank.values()) {
            groupUnion.sort((o1, o2) -> {
                int scoreCompare = o2.getGroupScore().compareTo(o1.getGroupScore());
                if (scoreCompare == 0) {
                    CrossPeakStrongholdUnionData unionData1 = getUnionData(o1.getUnionId());
                    CrossPeakStrongholdUnionData unionData2 = getUnionData(o2.getUnionId());
                    return unionData2.getAbility().compareTo(unionData1.getAbility());
                }
                return scoreCompare;
            });
            for (int i = 0; i < groupUnion.size(); i++) {
                int rank = i + 1;
                groupUnion.get(i).setGroupRank(rank);
            }
        }

        //初始化当前排行积分
        unionNowRankScoreRankList.clear();
        for (CrossPeakStrongholdUnionData unionData : unionScoreRankList) {
            unionNowRankScoreRankList.add(unionData);
        }
        updateNowScoreRank();

    }

    private void addRoundDamageRank(CrossPeakStrongholdDefendUnionData defendUnionData) {
        int group = defendUnionData.getGroup();
        List<CrossPeakStrongholdDefendUnionData> groupUnion = unionRoundDamageRank.get(group);
        if (null == groupUnion) {
            groupUnion = new ArrayList<>();
            unionRoundDamageRank.put(group, groupUnion);
        }
        if (!groupUnion.contains(defendUnionData)) {
            groupUnion.add(defendUnionData);
        }
    }

    public boolean isStageTypeNormal() {
        //等待状态修正到和config同步
        if (this.cacheData.getStageType() == config.getStageType().getValue() && this.cacheData.getRound() == config.getRound()) {
            return true;
        }
        if (Config.isDebug()) {
            CrossPeakStrongholdMgr.getLogger().info("等待状态修正到和config同步,目前状态roun{}={},时间状态round{}={}",
                    this.cacheData.getRound(), this.cacheData.getStageType(), config.getRound(), config.getStageType());
        }
        return false;
    }


    //更新配置
    public void setConfig(PeakStrongHoldConfig newConfig) {
        this.config = newConfig;
    }

    public void sendEliminateList(long serverId){
        if (!isStageTypeNormal()) {
            return;
        }
        MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(Protocol.S_PEAK_STRONGHOLD_ELIMINATE_UNION_LIST,
                CrossPeakStrongholdPb.buildEliminateUnionListMsg(unionScoreRankList, this.cacheData.getRound(), unionGroup)));
    }

    public int getActivityId() {
        return activityId;
    }

    public void updateGroupFirstDamageMember(int round,int group, PeakStrongholdUnionMemberInfo memberInfo) {
        if (0 == group) {
            return;
        }
        if (null == memberInfo) {
            return;
        }
        if (memberInfo.getRoundDamage().compareTo(BigInteger.ZERO) == 0) {
            return;
        }
        lockGroup(group);
        try {
            if(!groupFirstMemberMap.containsKey(round)){
                groupFirstMemberMap.put(round, new ConcurrentHashMap<>());
            }
            PeakStrongholdUnionMemberInfo firstMember = groupFirstMemberMap.get(round).get(group);
            if (null == firstMember) {
                groupFirstMemberMap.get(round).put(group, memberInfo);
            } else if (!firstMember.equals(memberInfo)) {
                if (firstMember.getRoundDamage().compareTo(memberInfo.getRoundDamage()) == -1) {
                    groupFirstMemberMap.get(round).put(group, memberInfo);
                }
            }
        } finally {
            unlockGroup(group);
        }
    }

    public static PeakStrongholdMemberDamage getUserDamage(List<PeakStrongholdMemberDamage> list, int round){
        if(list == null){
            return null;
        }
        for (PeakStrongholdMemberDamage damage : list) {
            if(damage.getRound() == round){
                return damage;
            }
        }
        return null;
    }

    public void viewUserDamageList(long serverId, long playerId, long targetUserId, String unionUid) {
        PeakStrongholdWarProto.PeakStrongholdUserRankDetailRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakStrongholdUserRankDetailRespMsg.newBuilder();
        if(!StringUtils.isNullOrEmpty(unionUid)) {
            CrossPeakStrongholdUnionData unionData = this.unionDataMap.get(unionUid);
            if(unionData != null){
                List<PeakStrongholdMemberDamage> memberDamageList = unionData.getMemberDamageMap().get(targetUserId);
                for (int i = 1; i <= cacheData.getRound(); i++) {
                    PeakStrongholdMemberDamage damage = getUserDamage(memberDamageList, i);
                    if(damage != null){
                        //历史回合
                        PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.Builder builder = PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.newBuilder();
                        builder.setRound(damage.getRound());
                        builder.setScore(-1);
                        builder.setGroup(damage.getGroupId());
                        builder.setDamage(damage.getDamage());
                        respMsg.addDetail(builder);
                    }else {
                        if(i == cacheData.getRound()){
                            //当前回合
                            PeakStrongholdUnionMemberInfo memberInfo = unionData.getMemberInfoMap().get(targetUserId);
                            if(memberInfo != null){
                                PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.Builder builder = PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.newBuilder();
                                builder.setRound(i);
                                builder.setScore(-1);
                                builder.setGroup(unionData.getGroup());
                                builder.setDamage(memberInfo.getRoundDamage().toString());
                                respMsg.addDetail(builder);
                            }else {
                                Map<String, CrossPeakStrongholdDefendUnionData> unionDataMap = defendUnionsMap.get(i);
                                if(unionDataMap != null) {
                                    CrossPeakStrongholdDefendUnionData roundUnionData = unionDataMap.get(unionUid);
                                    if (roundUnionData != null) {
                                        PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.Builder builder = PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.newBuilder();
                                        builder.setRound(i);
                                        builder.setScore(-1);
                                        builder.setGroup(unionData.getGroup());
                                        builder.setDamage("0");
                                        respMsg.addDetail(builder);
                                    }
                                }
                            }
                        }else {
                            //被淘汰回合
                            Map<String, CrossPeakStrongholdDefendUnionData> unionDataMap = defendUnionsMap.get(i);
                            if(unionDataMap != null){
                                CrossPeakStrongholdDefendUnionData roundUnionData = unionDataMap.get(unionUid);
                                if(roundUnionData == null){
                                    continue;
                                }
                            }
                            //历史回合未参与
                            PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.Builder builder = PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.newBuilder();
                            builder.setRound(i);
                            builder.setScore(-1);
                            builder.setGroup(unionData.getGroup());
                            builder.setDamage("0");
                            respMsg.addDetail(builder);
                        }
                    }
                }
            }
        }
        respMsg.setRet(0);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_RANK_USER_DAMAGE_DETAIL_LIST, respMsg));

    }

    /**
     * 商会伤害榜单
     */
    public void viewUnionRankScoreList(long serverId, long playerId, String unionUid) {
        PeakStrongholdWarProto.PeakStrongholdUnionRankDetailRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakStrongholdUnionRankDetailRespMsg.newBuilder();
        CrossPeakStrongholdUnionData unionData = unionDataMap.get(unionUid);
        if(unionData != null){
            for (int i = 1; i <= cacheData.getRound(); i++) {

                PeakStrongholdUnionDamage unionDamage = unionData.getUnionDamageMap().get(i);
                if(unionDamage != null){
                    PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.Builder builder = PeakStrongholdWarProto.PeakStrongholdRankDetailTemp.newBuilder();
                    builder.setRound(unionDamage.getRound());  //轮次
                    builder.setScore(unionDamage.getScore());     //积分
                    builder.setGroup(unionDamage.getGroup());      //分组
                    builder.setRankInGroup(unionDamage.getRankInGroup());  //组内排名
                    builder.setDamage(unionDamage.getDamage());
                    builder.setGroupScore(unionDamage.getGroupScore()); //组内伤害积分

                    if(i == cacheData.getRound()){
                        if (this.cacheData.getStageType() == ePeakStrongholdStageType.InBattle.getValue() ||
                            this.cacheData.getStageType() == ePeakStrongholdStageType.EndInShow.getValue()) {
                            CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(i, unionData.getUnionId());
                            if(defendUnionData != null){
                                BigInteger damage = BigInteger.ZERO;
                                for (Map.Entry<String, Map<Long, BigInteger>> entry : defendUnionData.getAttackUnionMap().entrySet()) {
                                    for (Map.Entry<Long, BigInteger> integerEntry : entry.getValue().entrySet()) {
                                        damage = damage.add(integerEntry.getValue());
                                    }
                                }
                                if (damage.compareTo(BigInteger.ZERO) > 0) {
                                    builder.setDamage(damage.toString());
                                }
                                builder.setRankInGroup(defendUnionData.getGroupRank());
                                builder.setGroupScore(defendUnionData.getGroupScore().toString());
                                PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), i);
                                if (null != timeConfig) {
                                    int score = timeConfig.getRankScore(defendUnionData.getGroupRank());
                                    builder.setScore(score);
                                }
                            }
                        } else {//当前轮，非开战期不显示
                            continue;
                        }
                    }
                    respMsg.addDetail(builder);
                }
            }
        }
        respMsg.setRet(0);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_RANK_UNION_DAMAGE_DETAIL_LIST, respMsg));

    }

    //开战期间的积分要算
    public BigInteger getNowScore(CrossPeakStrongholdUnionData unionData) {
        if (unionData == null) {
            return BigInteger.ZERO;
        }
        int round = this.cacheData.getRound();
        if (this.cacheData.getStageType() == ePeakStrongholdStageType.InBattle.getValue() && unionData.getLastRound() == round) {
            PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.InBattle.getValue(), round);
            CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(round, unionData.getUnionId());
            if (null == defendUnionData) {
                return BigInteger.ZERO;
            }
            int scoreAdd = timeConfig.getRankScore(defendUnionData.getGroupRank());
            BigInteger nowScore = unionData.getScore().add(BigInteger.valueOf(scoreAdd));
            return nowScore;
        } else {
            return unionData.getScore();
        }
    }

    public void updateNowScoreRank() {
        synchronized (unionNowRankScoreRankList) {
            for (CrossPeakStrongholdUnionData unionData : unionNowRankScoreRankList) {
                BigInteger nowRankScore = getNowScore(unionData);
                unionData.setNowRankScore(nowRankScore);
            }
            unionNowRankScoreRankList.sort(((o1, o2) -> {
                BigInteger nowScore1 = o1.getNowRankScore();
                BigInteger nowScore2 = o2.getNowRankScore();
                int compare = nowScore2.compareTo(nowScore1);
                if (0 == compare) {
                    BigInteger nowTotalGroupScore1 = o1.getTotalGroupScore();
                    BigInteger nowTotalGroupScore2 = o2.getTotalGroupScore();
                    CrossPeakStrongholdDefendUnionData defendUnionData1 = getDefendUnionData(this.cacheData.getRound(), o1.getUnionId());
                    if (defendUnionData1 != null) {
                        nowTotalGroupScore1 = o1.getTotalGroupScore().add(defendUnionData1.getGroupScore());
                    }
                    CrossPeakStrongholdDefendUnionData defendUnionData2 = getDefendUnionData(this.cacheData.getRound(), o2.getUnionId());
                    if (defendUnionData2 != null) {
                        nowTotalGroupScore2 = o2.getTotalGroupScore().add(defendUnionData2.getGroupScore());
                    }
                    compare = nowTotalGroupScore2.compareTo(nowTotalGroupScore1);
                    if (compare == 0) {
                        return o2.getAbility().compareTo(o1.getAbility());
                    }
                }
                return compare;
            }));
        }
        parseNowScoreRankListMsg();
    }

    public UnionActivityRankProto.UnionActivityRankListMsg getNowScoreUnionRankListMsg() {
        UnionActivityRankProto.UnionActivityRankListMsg rankListMsg = null;
        synchronized (nowScoreRankListMsg) {
            rankListMsg = this.nowScoreRankListMsg.build();
        }
        return rankListMsg;
    }

    public boolean isInBattle() {
        boolean isInBattle = false;
        synchronized (cacheData) {
            if (cacheData.getStageType() == ePeakStrongholdStageType.InBattle.getValue()) {
                isInBattle = true;
            }
        }
        return isInBattle;
    }

    private void parseNowScoreRankListMsg() {
        UnionActivityRankProto.UnionActivityRankListMsg.Builder builder = UnionActivityRankProto.UnionActivityRankListMsg.newBuilder();
        List<CrossPeakStrongholdUnionData> nowScoreRankList = new ArrayList<>();
        synchronized (unionNowRankScoreRankList) {
            nowScoreRankList.addAll(unionNowRankScoreRankList);
        }

        for (CrossPeakStrongholdUnionData unionData : nowScoreRankList) {

            UnionActivityRankProto.UnionActivityRankTempMsg.Builder rankMsg = UnionActivityRankProto.UnionActivityRankTempMsg.newBuilder();
            rankMsg.setUnionUid(unionData.getUnionId());
            rankMsg.setUnionBaseData(UnionBasePb.parseUnionBaseTempMsg(unionData.getUnionBaseInfo()));
            rankMsg.setValue(unionData.getNowRankScore().toString());
            BigInteger totalGroupScore = unionData.getTotalGroupScore();
            CrossPeakStrongholdDefendUnionData defendUnionData = getDefendUnionData(this.cacheData.getRound(), unionData.getUnionId());
            if (null != defendUnionData) {
                totalGroupScore = unionData.getTotalGroupScore().add(defendUnionData.getGroupScore());
            }
            rankMsg.setParamValue(totalGroupScore.toString());//显示的伤害由累计伤害改成累计伤害积分
            builder.addRankList(rankMsg);
        }
        synchronized (nowScoreRankListMsg) {
            this.nowScoreRankListMsg = builder;
        }
    }

    /**
     * 商会成员捐献经验详情
     */
    public void sendUnionMemberDonateExpList(long serverId, long userId, String unionId) {
        PeakStrongholdWarProto.PeakStrongholdUnionMemberDonateExpListRespMsg.Builder clientMsg = PeakStrongholdWarProto.PeakStrongholdUnionMemberDonateExpListRespMsg.newBuilder();
        clientMsg.setRet(0);
        clientMsg.setUnionId(unionId);
        lockUnion(unionId);
        try {
            CrossPeakStrongholdUnionData unionData = getUnionData(unionId);
            if (unionData != null) {
                for (PeakStrongholdUnionMemberInfo memberInfo : unionData.getMemberInfoMap().values()) {
                    PeakStrongholdWarProto.UnionMemberDonateExpTemp.Builder memberMsg = PeakStrongholdWarProto.UnionMemberDonateExpTemp.newBuilder();
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(memberInfo.getUserId());
                    if (null == userBaseInfo) {
                        continue;
                    }
                    memberMsg.setMemberName(userBaseInfo.getNickName());
                    memberMsg.setDonateExp(memberInfo.getDonateExp());
                    clientMsg.addMemberDonateExpList(memberMsg);
                }
            }
        } finally {
            unlockUnion(unionId);
        }

        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_PEAK_STRONGHOLD_MEMBER_DONATE_EXP_LIST, clientMsg));

    }

    public void lockRegistrationPromotionUnion(RankProto.CrossUnionRankListLockMsg lockMsg) {
        synchronized (abilityRankList) {
            if (!abilityRankList.isEmpty()) {
                //有名单了
                return;
            }
            //所有服的传完数据了,开始生成据点
            PeakStrongholdTimeConfig timeConfig = config.getTimeConfig(ePeakStrongholdStageType.Registration.getValue(), 0);
            if (null == timeConfig) {
                CrossPeakStrongholdMgr.getLogger().error("巅峰据点战 数据同步结束回合1开始, 取不到配置！异常！");
                return;//报错取不到配置！异常！
            }
            int rankNumLimit = Integer.parseInt(timeConfig.getParam());
            for (int i = 0; i < lockMsg.getRankList().size() && i < rankNumLimit; i++) {
                int rank = i + 1;
                RankProto.CrossUnionRankLockTemp unionRankLockTemp = lockMsg.getRankList().get(i);
                UnionBaseInfo unionBaseInfo = UnionBasePb.parseUnionBaseInfo(unionRankLockTemp.getRankTemp().getUnionBaseData());

                CrossUnionAbilityRankData rankData = new CrossUnionAbilityRankData();
                rankData.setInsertOption();
                rankData.setUnionId(unionRankLockTemp.getRankTemp().getUnionUid());
                rankData.setUnionBaseInfo(unionBaseInfo);
                rankData.setAbility(new BigInteger(unionRankLockTemp.getRankTemp().getValue()));
                rankData.setRank(rank);
                rankData.setRankId(rankData.getRank());
                rankData.setLastUpdateTime(System.currentTimeMillis());
                abilityRankList.add(rankData);
                abilityRankMap.put(rankData.getUnionId(), rankData);
            }

            //赚钱排行分组
            devideIntoGroupsByAbilityRank(timeConfig);
            unionScoreRankChangeSort();

            this.cacheData.setStageType(ePeakStrongholdStageType.HoldCreate.getValue());
            this.cacheData.setWaitError(0);
            this.cacheData.setRound(1);
            CrossPeakStrongholdMgr.getLogger().info("巅峰据点战 数据同步结束回合1开始, 等待据点数据生成！");
        }
    }

    public int getUnionGroup() {
        return unionGroup;
    }

    public String getUserAreaParam(long userId) {
        String unionUid = Cross2UnionActivityGroupMgr.getUnionUid(activityId, userId);
        CrossPeakStrongholdUnionData unionData = getUnionData(unionUid);
        if (unionData == null) {
            return null;
        }
        JSONObject json = new JSONObject();
        json.put("area", unionData.getGroup());
        return json.toJSONString();
    }
}
